<html lang="en">
<head>
<title>Bison 1.875</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Bison 1.875">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="top" href="#Top">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
This manual is for GNU Bison (version 1.875,
28 December 2002), the GNU parser generator.

Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998,
1999, 2000, 2001, 2002 Free Software Foundation, Inc.

     Permission is granted to copy, distribute and/or modify this
     document under the terms of the GNU Free Documentation License,
     Version 1.1 or any later version published by the Free Software
     Foundation; with no Invariant Sections, with the Front-Cover texts
     being "A GNU Manual," and with the Back-Cover Texts as in (a)
     below.  A copy of the license is included in the section entitled
     "GNU Free Documentation License."

     (a) The FSF's Back-Cover Text is: "You have freedom to copy and
     modify this GNU Manual, like GNU software.  Copies published by
     the Free Software Foundation raise funds for GNU development."
   -->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
  pre.display { font-family:inherit }
  pre.format  { font-family:inherit }
  pre.smalldisplay { font-family:inherit; font-size:smaller }
  pre.smallformat  { font-family:inherit; font-size:smaller }
  pre.smallexample { font-size:smaller }
  pre.smalllisp    { font-size:smaller }
  span.sc    { font-variant:small-caps }
  span.roman { font-family:serif; font-weight:normal; } 
  span.sansserif { font-family:sans-serif; font-weight:normal; } 
--></style>
</head>
<body>
<h1 class="settitle">Bison 1.875</h1>
<div class="contents">
<h2>Table of Contents</h2>
<ul>
<li><a name="toc_Top" href="#Top">Bison</a>
<li><a name="toc_Introduction" href="#Introduction">Introduction</a>
<li><a name="toc_Conditions" href="#Conditions">Conditions for Using Bison</a>
<li><a name="toc_Copying" href="#Copying">GNU GENERAL PUBLIC LICENSE</a>
<ul>
<li><a href="#Copying">Preamble</a>
<li><a href="#Copying">Appendix: How to Apply These Terms to Your New Programs</a>
</li></ul>
<li><a name="toc_Concepts" href="#Concepts">1 The Concepts of Bison</a>
<ul>
<li><a href="#Language-and-Grammar">1.1 Languages and Context-Free Grammars</a>
<li><a href="#Grammar-in-Bison">1.2 From Formal Rules to Bison Input</a>
<li><a href="#Semantic-Values">1.3 Semantic Values</a>
<li><a href="#Semantic-Actions">1.4 Semantic Actions</a>
<li><a href="#GLR-Parsers">1.5 Writing <acronym>GLR</acronym> Parsers</a>
<li><a href="#Locations-Overview">1.6 Locations</a>
<li><a href="#Bison-Parser">1.7 Bison Output: the Parser File</a>
<li><a href="#Stages">1.8 Stages in Using Bison</a>
<li><a href="#Grammar-Layout">1.9 The Overall Layout of a Bison Grammar</a>
</li></ul>
<li><a name="toc_Examples" href="#Examples">2 Examples</a>
<ul>
<li><a href="#RPN-Calc">2.1 Reverse Polish Notation Calculator</a>
<ul>
<li><a href="#Rpcalc-Decls">2.1.1 Declarations for <code>rpcalc</code></a>
<li><a href="#Rpcalc-Rules">2.1.2 Grammar Rules for <code>rpcalc</code></a>
<ul>
<li><a href="#Rpcalc-Input">2.1.2.1 Explanation of <code>input</code></a>
<li><a href="#Rpcalc-Line">2.1.2.2 Explanation of <code>line</code></a>
<li><a href="#Rpcalc-Expr">2.1.2.3 Explanation of <code>expr</code></a>
</li></ul>
<li><a href="#Rpcalc-Lexer">2.1.3 The <code>rpcalc</code> Lexical Analyzer</a>
<li><a href="#Rpcalc-Main">2.1.4 The Controlling Function</a>
<li><a href="#Rpcalc-Error">2.1.5 The Error Reporting Routine</a>
<li><a href="#Rpcalc-Gen">2.1.6 Running Bison to Make the Parser</a>
<li><a href="#Rpcalc-Compile">2.1.7 Compiling the Parser File</a>
</li></ul>
<li><a href="#Infix-Calc">2.2 Infix Notation Calculator: <code>calc</code></a>
<li><a href="#Simple-Error-Recovery">2.3 Simple Error Recovery</a>
<li><a href="#Location-Tracking-Calc">2.4 Location Tracking Calculator: <code>ltcalc</code></a>
<ul>
<li><a href="#Ltcalc-Decls">2.4.1 Declarations for <code>ltcalc</code></a>
<li><a href="#Ltcalc-Rules">2.4.2 Grammar Rules for <code>ltcalc</code></a>
<li><a href="#Ltcalc-Lexer">2.4.3 The <code>ltcalc</code> Lexical Analyzer.</a>
</li></ul>
<li><a href="#Multi_002dfunction-Calc">2.5 Multi-Function Calculator: <code>mfcalc</code></a>
<ul>
<li><a href="#Mfcalc-Decl">2.5.1 Declarations for <code>mfcalc</code></a>
<li><a href="#Mfcalc-Rules">2.5.2 Grammar Rules for <code>mfcalc</code></a>
<li><a href="#Mfcalc-Symtab">2.5.3 The <code>mfcalc</code> Symbol Table</a>
</li></ul>
<li><a href="#Exercises">2.6 Exercises</a>
</li></ul>
<li><a name="toc_Grammar-File" href="#Grammar-File">3 Bison Grammar Files</a>
<ul>
<li><a href="#Grammar-Outline">3.1 Outline of a Bison Grammar</a>
<ul>
<li><a href="#Prologue">3.1.1 The prologue</a>
<li><a href="#Bison-Declarations">3.1.2 The Bison Declarations Section</a>
<li><a href="#Grammar-Rules">3.1.3 The Grammar Rules Section</a>
<li><a href="#Epilogue">3.1.4 The epilogue</a>
</li></ul>
<li><a href="#Symbols">3.2 Symbols, Terminal and Nonterminal</a>
<li><a href="#Rules">3.3 Syntax of Grammar Rules</a>
<li><a href="#Recursion">3.4 Recursive Rules</a>
<li><a href="#Semantics">3.5 Defining Language Semantics</a>
<ul>
<li><a href="#Value-Type">3.5.1 Data Types of Semantic Values</a>
<li><a href="#Multiple-Types">3.5.2 More Than One Value Type</a>
<li><a href="#Actions">3.5.3 Actions</a>
<li><a href="#Action-Types">3.5.4 Data Types of Values in Actions</a>
<li><a href="#Mid_002dRule-Actions">3.5.5 Actions in Mid-Rule</a>
</li></ul>
<li><a href="#Locations">3.6 Tracking Locations</a>
<ul>
<li><a href="#Location-Type">3.6.1 Data Type of Locations</a>
<li><a href="#Actions-and-Locations">3.6.2 Actions and Locations</a>
<li><a href="#Location-Default-Action">3.6.3 Default Action for Locations</a>
</li></ul>
<li><a href="#Declarations">3.7 Bison Declarations</a>
<ul>
<li><a href="#Token-Decl">3.7.1 Token Type Names</a>
<li><a href="#Precedence-Decl">3.7.2 Operator Precedence</a>
<li><a href="#Union-Decl">3.7.3 The Collection of Value Types</a>
<li><a href="#Type-Decl">3.7.4 Nonterminal Symbols</a>
<li><a href="#Destructor-Decl">3.7.5 Freeing Discarded Symbols</a>
<li><a href="#Expect-Decl">3.7.6 Suppressing Conflict Warnings</a>
<li><a href="#Start-Decl">3.7.7 The Start-Symbol</a>
<li><a href="#Pure-Decl">3.7.8 A Pure (Reentrant) Parser</a>
<li><a href="#Decl-Summary">3.7.9 Bison Declaration Summary</a>
</li></ul>
<li><a href="#Multiple-Parsers">3.8 Multiple Parsers in the Same Program</a>
</li></ul>
<li><a name="toc_Interface" href="#Interface">4 Parser C-Language Interface</a>
<ul>
<li><a href="#Parser-Function">4.1 The Parser Function <code>yyparse</code></a>
<li><a href="#Lexical">4.2 The Lexical Analyzer Function <code>yylex</code></a>
<ul>
<li><a href="#Calling-Convention">4.2.1 Calling Convention for <code>yylex</code></a>
<li><a href="#Token-Values">4.2.2 Semantic Values of Tokens</a>
<li><a href="#Token-Positions">4.2.3 Textual Positions of Tokens</a>
<li><a href="#Pure-Calling">4.2.4 Calling Conventions for Pure Parsers</a>
</li></ul>
<li><a href="#Error-Reporting">4.3 The Error Reporting Function <code>yyerror</code></a>
<li><a href="#Action-Features">4.4 Special Features for Use in Actions</a>
</li></ul>
<li><a name="toc_Algorithm" href="#Algorithm">5 The Bison Parser Algorithm</a>
<ul>
<li><a href="#Look_002dAhead">5.1 Look-Ahead Tokens</a>
<li><a href="#Shift_002fReduce">5.2 Shift/Reduce Conflicts</a>
<li><a href="#Precedence">5.3 Operator Precedence</a>
<ul>
<li><a href="#Why-Precedence">5.3.1 When Precedence is Needed</a>
<li><a href="#Using-Precedence">5.3.2 Specifying Operator Precedence</a>
<li><a href="#Precedence-Examples">5.3.3 Precedence Examples</a>
<li><a href="#How-Precedence">5.3.4 How Precedence Works</a>
</li></ul>
<li><a href="#Contextual-Precedence">5.4 Context-Dependent Precedence</a>
<li><a href="#Parser-States">5.5 Parser States</a>
<li><a href="#Reduce_002fReduce">5.6 Reduce/Reduce Conflicts</a>
<li><a href="#Mystery-Conflicts">5.7 Mysterious Reduce/Reduce Conflicts</a>
<li><a href="#Generalized-LR-Parsing">5.8 Generalized <acronym>LR</acronym> (<acronym>GLR</acronym>) Parsing</a>
<li><a href="#Stack-Overflow">5.9 Stack Overflow, and How to Avoid It</a>
</li></ul>
<li><a name="toc_Error-Recovery" href="#Error-Recovery">6 Error Recovery</a>
<li><a name="toc_Context-Dependency" href="#Context-Dependency">7 Handling Context Dependencies</a>
<ul>
<li><a href="#Semantic-Tokens">7.1 Semantic Info in Token Types</a>
<li><a href="#Lexical-Tie_002dins">7.2 Lexical Tie-ins</a>
<li><a href="#Tie_002din-Recovery">7.3 Lexical Tie-ins and Error Recovery</a>
</li></ul>
<li><a name="toc_Debugging" href="#Debugging">8 Debugging Your Parser</a>
<ul>
<li><a href="#Understanding">8.1 Understanding Your Parser</a>
<li><a href="#Tracing">8.2 Tracing Your Parser</a>
</li></ul>
<li><a name="toc_Invocation" href="#Invocation">9 Invoking Bison</a>
<ul>
<li><a href="#Bison-Options">9.1 Bison Options</a>
<li><a href="#Option-Cross-Key">9.2 Option Cross Key</a>
<li><a href="#Yacc-Library">9.3 Yacc Library</a>
</li></ul>
<li><a name="toc_FAQ" href="#FAQ">10 Frequently Asked Questions</a>
<ul>
<li><a href="#Parser-Stack-Overflow">10.1 Parser Stack Overflow</a>
</li></ul>
<li><a name="toc_Table-of-Symbols" href="#Table-of-Symbols">Appendix A Bison Symbols</a>
<li><a name="toc_Glossary" href="#Glossary">Appendix B Glossary</a>
<li><a name="toc_Copying-This-Manual" href="#Copying-This-Manual">Appendix C Copying This Manual</a>
<ul>
<li><a href="#GNU-Free-Documentation-License">C.1 GNU Free Documentation License</a>
<ul>
<li><a href="#GNU-Free-Documentation-License">C.1.1 ADDENDUM: How to use this License for your documents</a>
</li></ul>
</li></ul>
<li><a name="toc_Index" href="#Index">Index</a>
</li></ul>
</div>



<div class="node">
<p><hr>
<a name="Top"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Introduction">Introduction</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#dir">(dir)</a>

</div>

<h2 class="unnumbered">Bison</h2>

<p>This manual is for <acronym>GNU</acronym> Bison (version 1.875,
28 December 2002), the <acronym>GNU</acronym> parser generator.

   <p>Copyright &copy; 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998,
1999, 2000, 2001, 2002 Free Software Foundation, Inc.

   <blockquote>
Permission is granted to copy, distribute and/or modify this document
under the terms of the <acronym>GNU</acronym> Free Documentation License,
Version 1.1 or any later version published by the Free Software
Foundation; with no Invariant Sections, with the Front-Cover texts
being &ldquo;A <acronym>GNU</acronym> Manual,&rdquo; and with the Back-Cover Texts as in
(a) below.  A copy of the license is included in the section entitled
&ldquo;<acronym>GNU</acronym> Free Documentation License.&rdquo;

        <p>(a) The <acronym>FSF</acronym>'s Back-Cover Text is: &ldquo;You have freedom to copy
and modify this <acronym>GNU</acronym> Manual, like <acronym>GNU</acronym> software. 
Copies published by the Free Software Foundation raise funds for
<acronym>GNU</acronym> development.&rdquo;
</blockquote>

<ul class="menu">
<li><a accesskey="1" href="#Introduction">Introduction</a>
<li><a accesskey="2" href="#Conditions">Conditions</a>
<li><a accesskey="3" href="#Copying">Copying</a>:            The <acronym>GNU</acronym> General Public License says
                        how you can copy and share Bison

</li></ul>
<p>Tutorial sections:
</p>
<ul class="menu">
<li><a accesskey="4" href="#Concepts">Concepts</a>:           Basic concepts for understanding Bison. 
<li><a accesskey="5" href="#Examples">Examples</a>:           Three simple explained examples of using Bison.

</li></ul>
<p>Reference sections:
</p>
<ul class="menu">
<li><a accesskey="6" href="#Grammar-File">Grammar File</a>:       Writing Bison declarations and rules. 
<li><a accesskey="7" href="#Interface">Interface</a>:          C-language interface to the parser function <code>yyparse</code>. 
<li><a accesskey="8" href="#Algorithm">Algorithm</a>:          How the Bison parser works at run-time. 
<li><a accesskey="9" href="#Error-Recovery">Error Recovery</a>:     Writing rules for error recovery. 
<li><a href="#Context-Dependency">Context Dependency</a>:   What to do if your language syntax is too
                        messy for Bison to handle straightforwardly. 
<li><a href="#Debugging">Debugging</a>:          Understanding or debugging Bison parsers. 
<li><a href="#Invocation">Invocation</a>:         How to run Bison (to produce the parser source file). 
<li><a href="#Table-of-Symbols">Table of Symbols</a>:   All the keywords of the Bison language are explained. 
<li><a href="#Glossary">Glossary</a>:           Basic concepts are explained. 
<li><a href="#FAQ">FAQ</a>:                Frequently Asked Questions
<li><a href="#Copying-This-Manual">Copying This Manual</a>:   License for copying this manual. 
<li><a href="#Index">Index</a>:              Cross-references to the text.

</li></ul>
<p>--- The Detailed Node Listing ---

<p>The Concepts of Bison

</p>
<ul class="menu">
<li><a href="#Language-and-Grammar">Language and Grammar</a>:   Languages and context-free grammars,
                            as mathematical ideas. 
<li><a href="#Grammar-in-Bison">Grammar in Bison</a>:   How we represent grammars for Bison's sake. 
<li><a href="#Semantic-Values">Semantic Values</a>:    Each token or syntactic grouping can have
                        a semantic value (the value of an integer,
                        the name of an identifier, etc.). 
<li><a href="#Semantic-Actions">Semantic Actions</a>:   Each rule can have an action containing C code. 
<li><a href="#GLR-Parsers">GLR Parsers</a>:        Writing parsers for general context-free languages
<li><a href="#Locations-Overview">Locations Overview</a>:     Tracking Locations. 
<li><a href="#Bison-Parser">Bison Parser</a>:       What are Bison's input and output,
                        how is the output used? 
<li><a href="#Stages">Stages</a>:             Stages in writing and running Bison grammars. 
<li><a href="#Grammar-Layout">Grammar Layout</a>:     Overall structure of a Bison grammar file.

</li></ul>
<p>Examples

</p>
<ul class="menu">
<li><a href="#RPN-Calc">RPN Calc</a>:           Reverse polish notation calculator;
                        a first example with no operator precedence. 
<li><a href="#Infix-Calc">Infix Calc</a>:         Infix (algebraic) notation calculator. 
                        Operator precedence is introduced. 
<li><a href="#Simple-Error-Recovery">Simple Error Recovery</a>:   Continuing after syntax errors. 
<li><a href="#Location-Tracking-Calc">Location Tracking Calc</a>:  Demonstrating the use of @<var>n</var> and @$. 
<li><a href="#Multi_002dfunction-Calc">Multi-function Calc</a>:   Calculator with memory and trig functions. 
                           It uses multiple data-types for semantic values. 
<li><a href="#Exercises">Exercises</a>:          Ideas for improving the multi-function calculator.

</li></ul>
<p>Reverse Polish Notation Calculator

</p>
<ul class="menu">
<li><a href="#Rpcalc-Decls">Decls</a>:   Prologue (declarations) for rpcalc. 
<li><a href="#Rpcalc-Rules">Rules</a>:   Grammar Rules for rpcalc, with explanation. 
<li><a href="#Rpcalc-Lexer">Lexer</a>:   The lexical analyzer. 
<li><a href="#Rpcalc-Main">Main</a>:     The controlling function. 
<li><a href="#Rpcalc-Error">Error</a>:   The error reporting function. 
<li><a href="#Rpcalc-Gen">Gen</a>:       Running Bison on the grammar file. 
<li><a href="#Rpcalc-Compile">Comp</a>:  Run the C compiler on the output code.

</li></ul>
<p>Grammar Rules for <code>rpcalc</code>

</p>
<ul class="menu">
<li><a href="#Rpcalc-Input">Rpcalc Input</a>
<li><a href="#Rpcalc-Line">Rpcalc Line</a>
<li><a href="#Rpcalc-Expr">Rpcalc Expr</a>

</li></ul>
<p>Location Tracking Calculator: <code>ltcalc</code>

</p>
<ul class="menu">
<li><a href="#Ltcalc-Decls">Decls</a>:   Bison and C declarations for ltcalc. 
<li><a href="#Ltcalc-Rules">Rules</a>:   Grammar rules for ltcalc, with explanations. 
<li><a href="#Ltcalc-Lexer">Lexer</a>:   The lexical analyzer.

</li></ul>
<p>Multi-Function Calculator: <code>mfcalc</code>

</p>
<ul class="menu">
<li><a href="#Mfcalc-Decl">Decl</a>:       Bison declarations for multi-function calculator. 
<li><a href="#Mfcalc-Rules">Rules</a>:     Grammar rules for the calculator. 
<li><a href="#Mfcalc-Symtab">Symtab</a>:   Symbol table management subroutines.

</li></ul>
<p>Bison Grammar Files

</p>
<ul class="menu">
<li><a href="#Grammar-Outline">Grammar Outline</a>:    Overall layout of the grammar file. 
<li><a href="#Symbols">Symbols</a>:            Terminal and nonterminal symbols. 
<li><a href="#Rules">Rules</a>:              How to write grammar rules. 
<li><a href="#Recursion">Recursion</a>:          Writing recursive rules. 
<li><a href="#Semantics">Semantics</a>:          Semantic values and actions. 
<li><a href="#Locations">Locations</a>:          Locations and actions. 
<li><a href="#Declarations">Declarations</a>:       All kinds of Bison declarations are described here. 
<li><a href="#Multiple-Parsers">Multiple Parsers</a>:   Putting more than one Bison parser in one program.

</li></ul>
<p>Outline of a Bison Grammar

</p>
<ul class="menu">
<li><a href="#Prologue">Prologue</a>:           Syntax and usage of the prologue. 
<li><a href="#Bison-Declarations">Bison Declarations</a>:   Syntax and usage of the Bison declarations section. 
<li><a href="#Grammar-Rules">Grammar Rules</a>:      Syntax and usage of the grammar rules section. 
<li><a href="#Epilogue">Epilogue</a>:           Syntax and usage of the epilogue.

</li></ul>
<p>Defining Language Semantics

</p>
<ul class="menu">
<li><a href="#Value-Type">Value Type</a>:         Specifying one data type for all semantic values. 
<li><a href="#Multiple-Types">Multiple Types</a>:     Specifying several alternative data types. 
<li><a href="#Actions">Actions</a>:            An action is the semantic definition of a grammar rule. 
<li><a href="#Action-Types">Action Types</a>:       Specifying data types for actions to operate on. 
<li><a href="#Mid_002dRule-Actions">Mid-Rule Actions</a>:   Most actions go at the end of a rule. 
                      This says when, why and how to use the exceptional
                        action in the middle of a rule.

</li></ul>
<p>Tracking Locations

</p>
<ul class="menu">
<li><a href="#Location-Type">Location Type</a>:                Specifying a data type for locations. 
<li><a href="#Actions-and-Locations">Actions and Locations</a>:        Using locations in actions. 
<li><a href="#Location-Default-Action">Location Default Action</a>:      Defining a general way to compute locations.

</li></ul>
<p>Bison Declarations

</p>
<ul class="menu">
<li><a href="#Token-Decl">Token Decl</a>:         Declaring terminal symbols. 
<li><a href="#Precedence-Decl">Precedence Decl</a>:    Declaring terminals with precedence and associativity. 
<li><a href="#Union-Decl">Union Decl</a>:         Declaring the set of all semantic value types. 
<li><a href="#Type-Decl">Type Decl</a>:          Declaring the choice of type for a nonterminal symbol. 
<li><a href="#Destructor-Decl">Destructor Decl</a>:    Declaring how symbols are freed. 
<li><a href="#Expect-Decl">Expect Decl</a>:        Suppressing warnings about shift/reduce conflicts. 
<li><a href="#Start-Decl">Start Decl</a>:         Specifying the start symbol. 
<li><a href="#Pure-Decl">Pure Decl</a>:          Requesting a reentrant parser. 
<li><a href="#Decl-Summary">Decl Summary</a>:       Table of all Bison declarations.

</li></ul>
<p>Parser C-Language Interface

</p>
<ul class="menu">
<li><a href="#Parser-Function">Parser Function</a>:    How to call <code>yyparse</code> and what it returns. 
<li><a href="#Lexical">Lexical</a>:            You must supply a function <code>yylex</code>
                        which reads tokens. 
<li><a href="#Error-Reporting">Error Reporting</a>:    You must supply a function <code>yyerror</code>. 
<li><a href="#Action-Features">Action Features</a>:    Special features for use in actions.

</li></ul>
<p>The Lexical Analyzer Function <code>yylex</code>

</p>
<ul class="menu">
<li><a href="#Calling-Convention">Calling Convention</a>:   How <code>yyparse</code> calls <code>yylex</code>. 
<li><a href="#Token-Values">Token Values</a>:       How <code>yylex</code> must return the semantic value
                        of the token it has read. 
<li><a href="#Token-Positions">Token Positions</a>:    How <code>yylex</code> must return the text position
                        (line number, etc.) of the token, if the
                        actions want that. 
<li><a href="#Pure-Calling">Pure Calling</a>:       How the calling convention differs
                        in a pure parser (see <a href="#Pure-Decl">A Pure (Reentrant) Parser</a>).

</li></ul>
<p>The Bison Parser Algorithm

</p>
<ul class="menu">
<li><a href="#Look_002dAhead">Look-Ahead</a>:         Parser looks one token ahead when deciding what to do. 
<li><a href="#Shift_002fReduce">Shift/Reduce</a>:       Conflicts: when either shifting or reduction is valid. 
<li><a href="#Precedence">Precedence</a>:         Operator precedence works by resolving conflicts. 
<li><a href="#Contextual-Precedence">Contextual Precedence</a>:   When an operator's precedence depends on context. 
<li><a href="#Parser-States">Parser States</a>:      The parser is a finite-state-machine with stack. 
<li><a href="#Reduce_002fReduce">Reduce/Reduce</a>:      When two rules are applicable in the same situation. 
<li><a href="#Mystery-Conflicts">Mystery Conflicts</a>:   Reduce/reduce conflicts that look unjustified. 
<li><a href="#Generalized-LR-Parsing">Generalized LR Parsing</a>:   Parsing arbitrary context-free grammars. 
<li><a href="#Stack-Overflow">Stack Overflow</a>:     What happens when stack gets full.  How to avoid it.

</li></ul>
<p>Operator Precedence

</p>
<ul class="menu">
<li><a href="#Why-Precedence">Why Precedence</a>:     An example showing why precedence is needed. 
<li><a href="#Using-Precedence">Using Precedence</a>:   How to specify precedence in Bison grammars. 
<li><a href="#Precedence-Examples">Precedence Examples</a>:   How these features are used in the previous example. 
<li><a href="#How-Precedence">How Precedence</a>:     How they work.

</li></ul>
<p>Handling Context Dependencies

</p>
<ul class="menu">
<li><a href="#Semantic-Tokens">Semantic Tokens</a>:    Token parsing can depend on the semantic context. 
<li><a href="#Lexical-Tie_002dins">Lexical Tie-ins</a>:    Token parsing can depend on the syntactic context. 
<li><a href="#Tie_002din-Recovery">Tie-in Recovery</a>:    Lexical tie-ins have implications for how
                        error recovery rules must be written.

</li></ul>
<p>Debugging Your Parser

</p>
<ul class="menu">
<li><a href="#Understanding">Understanding</a>:      Understanding the structure of your parser. 
<li><a href="#Tracing">Tracing</a>:            Tracing the execution of your parser.

</li></ul>
<p>Invoking Bison

</p>
<ul class="menu">
<li><a href="#Bison-Options">Bison Options</a>:      All the options described in detail,
                        in alphabetical order by short options. 
<li><a href="#Option-Cross-Key">Option Cross Key</a>:   Alphabetical list of long options. 
<li><a href="#Yacc-Library">Yacc Library</a>:       Yacc-compatible <code>yylex</code> and <code>main</code>.

</li></ul>
<p>Frequently Asked Questions

</p>
<ul class="menu">
<li><a href="#Parser-Stack-Overflow">Parser Stack Overflow</a>:       Breaking the Stack Limits

</li></ul>
<p>Copying This Manual

</p>
<ul class="menu">
<li><a href="#GNU-Free-Documentation-License">GNU Free Documentation License</a>:   License for copying this manual.

   </ul>

<div class="node">
<p><hr>
<a name="Introduction"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Conditions">Conditions</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Top">Top</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="unnumbered">Introduction</h2>

<p><a name="index-introduction-1"></a>
<dfn>Bison</dfn> is a general-purpose parser generator that converts a
grammar description for an <acronym>LALR</acronym>(1) context-free grammar into a C
program to parse that grammar.  Once you are proficient with Bison,
you may use it to develop a wide range of language parsers, from those
used in simple desk calculators to complex programming languages.

   <p>Bison is upward compatible with Yacc: all properly-written Yacc grammars
ought to work with Bison with no change.  Anyone familiar with Yacc
should be able to use Bison with little trouble.  You need to be fluent in
C programming in order to use Bison or to understand this manual.

   <p>We begin with tutorial chapters that explain the basic concepts of using
Bison and show three explained examples, each building on the last.  If you
don't know Bison or Yacc, start by reading these chapters.  Reference
chapters follow which describe specific aspects of Bison in detail.

   <p>Bison was written primarily by Robert Corbett; Richard Stallman made it
Yacc-compatible.  Wilfred Hansen of Carnegie Mellon University added
multi-character string literals and other features.

   <p>This edition corresponds to version 1.875 of Bison.

<div class="node">
<p><hr>
<a name="Conditions"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Copying">Copying</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Introduction">Introduction</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="unnumbered">Conditions for Using Bison</h2>

<p>As of Bison version 1.24, we have changed the distribution terms for
<code>yyparse</code> to permit using Bison's output in nonfree programs when
Bison is generating C code for <acronym>LALR</acronym>(1) parsers.  Formerly, these
parsers could be used only in programs that were free software.

   <p>The other <acronym>GNU</acronym> programming tools, such as the <acronym>GNU</acronym> C
compiler, have never
had such a requirement.  They could always be used for nonfree
software.  The reason Bison was different was not due to a special
policy decision; it resulted from applying the usual General Public
License to all of the Bison source code.

   <p>The output of the Bison utility&mdash;the Bison parser file&mdash;contains a
verbatim copy of a sizable piece of Bison, which is the code for the
<code>yyparse</code> function.  (The actions from your grammar are inserted
into this function at one point, but the rest of the function is not
changed.)  When we applied the <acronym>GPL</acronym> terms to the code for
<code>yyparse</code>,
the effect was to restrict the use of Bison output to free software.

   <p>We didn't change the terms because of sympathy for people who want to
make software proprietary.  <strong>Software should be free.</strong>  But we
concluded that limiting Bison's use to free software was doing little to
encourage people to make other software free.  So we decided to make the
practical conditions for using Bison match the practical conditions for
using the other <acronym>GNU</acronym> tools.

   <p>This exception applies only when Bison is generating C code for a
<acronym>LALR</acronym>(1) parser; otherwise, the <acronym>GPL</acronym> terms operate
as usual.  You can
tell whether the exception applies to your `<samp><span class="samp">.c</span></samp>' output file by
inspecting it to see whether it says &ldquo;As a special exception, when
this file is copied by Bison into a Bison output file, you may use
that output file without restriction.&rdquo;

<div class="node">
<p><hr>
<a name="Copying"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Concepts">Concepts</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Conditions">Conditions</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="unnumbered">GNU GENERAL PUBLIC LICENSE</h2>

<div align="center">Version 2, June 1991</div>

<!-- This file is intended to be included in another file. -->
<pre class="display">     Copyright &copy; 1989, 1991 Free Software Foundation, Inc.
     59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
     
     Everyone is permitted to copy and distribute verbatim copies
     of this license document, but changing it is not allowed.
</pre>
   <h3 class="unnumberedsec">Preamble</h3>

<p>The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software&mdash;to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.)  You can apply it to
your programs, too.

   <p>When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

   <p>To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights. 
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

   <p>For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

   <p>We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

   <p>Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

   <p>Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

   <p>The precise terms and conditions for copying, distribution and
modification follow.

     <ol type=1 start=0>
<li>This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The &ldquo;Program&rdquo;, below,
refers to any such program or work, and a &ldquo;work based on the Program&rdquo;
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term &ldquo;modification&rdquo;.)  Each licensee is addressed as &ldquo;you&rdquo;.

     <p>Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program). 
Whether that is true depends on what the Program does.

     <li>You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

     <p>You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

     <li>You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

          <ol type=a start=1>
<li>You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.

          <li>You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.

          <li>If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License.  (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
          </ol>

     <p>These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

     <p>Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

     <p>In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

     <li>You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

          <ol type=a start=1>
<li>Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,

          <li>Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,

          <li>Accompany it with the information you received as to the offer
to distribute corresponding source code.  (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
          </ol>

     <p>The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

     <p>If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

     <li>You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License. 
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

     <li>You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

     <li>Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein. 
You are not responsible for enforcing compliance by third parties to
this License.

     <li>If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

     <p>If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

     <p>It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

     <p>This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

     <li>If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

     <li>The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

     <p>Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and &ldquo;any
later version&rdquo;, you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

     <li>If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

     <li>BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM &ldquo;AS IS&rdquo; WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

     <li>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
        </ol>

<h3 class="unnumberedsec">Appendix: How to Apply These Terms to Your New Programs</h3>

<p>If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

   <p>To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the &ldquo;copyright&rdquo; line and a pointer to where the full notice is found.

<pre class="smallexample">     <var>one line to give the program's name and a brief idea of what it does.</var>
     Copyright (C) <var>yyyy</var>  <var>name of author</var>
     
     This program is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
     the Free Software Foundation; either version 2 of the License, or
     (at your option) any later version.
     
     This program is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU General Public License for more details.
     
     You should have received a copy of the GNU General Public License
     along with this program; if not, write to the Free Software
     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
</pre>
   <p>Also add information on how to contact you by electronic and paper mail.

   <p>If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

<pre class="smallexample">     Gnomovision version 69, Copyright (C) 19<var>yy</var> <var>name of author</var>
     Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
     This is free software, and you are welcome to redistribute it
     under certain conditions; type `show c' for details.
</pre>
   <p>The hypothetical commands `<samp><span class="samp">show w</span></samp>' and `<samp><span class="samp">show c</span></samp>' should show
the appropriate parts of the General Public License.  Of course, the
commands you use may be called something other than `<samp><span class="samp">show w</span></samp>' and
`<samp><span class="samp">show c</span></samp>'; they could even be mouse-clicks or menu items&mdash;whatever
suits your program.

   <p>You should also get your employer (if you work as a programmer) or your
school, if any, to sign a &ldquo;copyright disclaimer&rdquo; for the program, if
necessary.  Here is a sample; alter the names:

<pre class="example">     Yoyodyne, Inc., hereby disclaims all copyright interest in the program
     `Gnomovision' (which makes passes at compilers) written by James Hacker.
     
     <var>signature of Ty Coon</var>, 1 April 1989
     Ty Coon, President of Vice
</pre>
   <p>This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Library General
Public License instead of this License.

<div class="node">
<p><hr>
<a name="Concepts"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Examples">Examples</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Copying">Copying</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="chapter">1 The Concepts of Bison</h2>

<p>This chapter introduces many of the basic concepts without which the
details of Bison will not make sense.  If you do not already know how to
use Bison or Yacc, we suggest you start by reading this chapter carefully.

<ul class="menu">
<li><a accesskey="1" href="#Language-and-Grammar">Language and Grammar</a>:   Languages and context-free grammars,
                            as mathematical ideas. 
<li><a accesskey="2" href="#Grammar-in-Bison">Grammar in Bison</a>:   How we represent grammars for Bison's sake. 
<li><a accesskey="3" href="#Semantic-Values">Semantic Values</a>:    Each token or syntactic grouping can have
                        a semantic value (the value of an integer,
                        the name of an identifier, etc.). 
<li><a accesskey="4" href="#Semantic-Actions">Semantic Actions</a>:   Each rule can have an action containing C code. 
<li><a accesskey="5" href="#GLR-Parsers">GLR Parsers</a>:        Writing parsers for general context-free languages
<li><a accesskey="6" href="#Locations-Overview">Locations Overview</a>:     Tracking Locations. 
<li><a accesskey="7" href="#Bison-Parser">Bison Parser</a>:       What are Bison's input and output,
                        how is the output used? 
<li><a accesskey="8" href="#Stages">Stages</a>:             Stages in writing and running Bison grammars. 
<li><a accesskey="9" href="#Grammar-Layout">Grammar Layout</a>:     Overall structure of a Bison grammar file. 
</ul>

<div class="node">
<p><hr>
<a name="Language-and-Grammar"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Grammar-in-Bison">Grammar in Bison</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Concepts">Concepts</a>

</div>

<h3 class="section">1.1 Languages and Context-Free Grammars</h3>

<p><a name="index-context_002dfree-grammar-2"></a><a name="index-grammar_002c-context_002dfree-3"></a>In order for Bison to parse a language, it must be described by a
<dfn>context-free grammar</dfn>.  This means that you specify one or more
<dfn>syntactic groupings</dfn> and give rules for constructing them from their
parts.  For example, in the C language, one kind of grouping is called an
`expression'.  One rule for making an expression might be, &ldquo;An expression
can be made of a minus sign and another expression&rdquo;.  Another would be,
&ldquo;An expression can be an integer&rdquo;.  As you can see, rules are often
recursive, but there must be at least one rule which leads out of the
recursion.

   <p><a name="index-g_t_0040acronym_007bBNF_007d-4"></a><a name="index-Backus_002dNaur-form-5"></a>The most common formal system for presenting such rules for humans to read
is <dfn>Backus-Naur Form</dfn> or &ldquo;<acronym>BNF</acronym>&rdquo;, which was developed in
order to specify the language Algol 60.  Any grammar expressed in
<acronym>BNF</acronym> is a context-free grammar.  The input to Bison is
essentially machine-readable <acronym>BNF</acronym>.

   <p><a name="index-g_t_0040acronym_007bLALR_007d_00281_0029-grammars-6"></a><a name="index-g_t_0040acronym_007bLR_007d_00281_0029-grammars-7"></a>There are various important subclasses of context-free grammar.  Although it
can handle almost all context-free grammars, Bison is optimized for what
are called <acronym>LALR</acronym>(1) grammars. 
In brief, in these grammars, it must be possible to
tell how to parse any portion of an input string with just a single
token of look-ahead.  Strictly speaking, that is a description of an
<acronym>LR</acronym>(1) grammar, and <acronym>LALR</acronym>(1) involves additional
restrictions that are
hard to explain simply; but it is rare in actual practice to find an
<acronym>LR</acronym>(1) grammar that fails to be <acronym>LALR</acronym>(1). 
See <a href="#Mystery-Conflicts">Mysterious Reduce/Reduce Conflicts</a>, for
more information on this.

   <p><a name="index-g_t_0040acronym_007bGLR_007d-parsing-8"></a><a name="index-generalized-_0040acronym_007bLR_007d-_0028_0040acronym_007bGLR_007d_0029-parsing-9"></a><a name="index-ambiguous-grammars-10"></a><a name="index-non_002ddeterministic-parsing-11"></a>
Parsers for <acronym>LALR</acronym>(1) grammars are <dfn>deterministic</dfn>, meaning
roughly that the next grammar rule to apply at any point in the input is
uniquely determined by the preceding input and a fixed, finite portion
(called a <dfn>look-ahead</dfn>) of the remaining input.  A context-free
grammar can be <dfn>ambiguous</dfn>, meaning that there are multiple ways to
apply the grammar rules to get the some inputs.  Even unambiguous
grammars can be <dfn>non-deterministic</dfn>, meaning that no fixed
look-ahead always suffices to determine the next grammar rule to apply. 
With the proper declarations, Bison is also able to parse these more
general context-free grammars, using a technique known as <acronym>GLR</acronym>
parsing (for Generalized <acronym>LR</acronym>).  Bison's <acronym>GLR</acronym> parsers
are able to handle any context-free grammar for which the number of
possible parses of any given string is finite.

   <p><a name="index-symbols-_0028abstract_0029-12"></a><a name="index-token-13"></a><a name="index-syntactic-grouping-14"></a><a name="index-grouping_002c-syntactic-15"></a>In the formal grammatical rules for a language, each kind of syntactic
unit or grouping is named by a <dfn>symbol</dfn>.  Those which are built by
grouping smaller constructs according to grammatical rules are called
<dfn>nonterminal symbols</dfn>; those which can't be subdivided are called
<dfn>terminal symbols</dfn> or <dfn>token types</dfn>.  We call a piece of input
corresponding to a single terminal symbol a <dfn>token</dfn>, and a piece
corresponding to a single nonterminal symbol a <dfn>grouping</dfn>.

   <p>We can use the C language as an example of what symbols, terminal and
nonterminal, mean.  The tokens of C are identifiers, constants (numeric
and string), and the various keywords, arithmetic operators and
punctuation marks.  So the terminal symbols of a grammar for C include
`identifier', `number', `string', plus one symbol for each keyword,
operator or punctuation mark: `if', `return', `const', `static', `int',
`char', `plus-sign', `open-brace', `close-brace', `comma' and many more. 
(These tokens can be subdivided into characters, but that is a matter of
lexicography, not grammar.)

   <p>Here is a simple C function subdivided into tokens:

<pre class="example">     int             /* <span class="roman">keyword `int'</span> */
     square (int x)  /* <span class="roman">identifier, open-paren, identifier, identifier, close-paren</span> */
     {               /* <span class="roman">open-brace</span> */
       return x * x; /* <span class="roman">keyword `return', identifier, asterisk, identifier, semicolon</span> */
     }               /* <span class="roman">close-brace</span> */
</pre>
   <p>The syntactic groupings of C include the expression, the statement, the
declaration, and the function definition.  These are represented in the
grammar of C by nonterminal symbols `expression', `statement',
`declaration' and `function definition'.  The full grammar uses dozens of
additional language constructs, each with its own nonterminal symbol, in
order to express the meanings of these four.  The example above is a
function definition; it contains one declaration, and one statement.  In
the statement, each `<samp><span class="samp">x</span></samp>' is an expression and so is `<samp><span class="samp">x * x</span></samp>'.

   <p>Each nonterminal symbol must have grammatical rules showing how it is made
out of simpler constructs.  For example, one kind of C statement is the
<code>return</code> statement; this would be described with a grammar rule which
reads informally as follows:

   <blockquote>
A `statement' can be made of a `return' keyword, an `expression' and a
`semicolon'. 
</blockquote>

<p class="noindent">There would be many other rules for `statement', one for each kind of
statement in C.

   <p><a name="index-start-symbol-16"></a>One nonterminal symbol must be distinguished as the special one which
defines a complete utterance in the language.  It is called the <dfn>start
symbol</dfn>.  In a compiler, this means a complete input program.  In the C
language, the nonterminal symbol `sequence of definitions and declarations'
plays this role.

   <p>For example, `<samp><span class="samp">1 + 2</span></samp>' is a valid C expression&mdash;a valid part of a C
program&mdash;but it is not valid as an <em>entire</em> C program.  In the
context-free grammar of C, this follows from the fact that `expression' is
not the start symbol.

   <p>The Bison parser reads a sequence of tokens as its input, and groups the
tokens using the grammar rules.  If the input is valid, the end result is
that the entire token sequence reduces to a single grouping whose symbol is
the grammar's start symbol.  If we use a grammar for C, the entire input
must be a `sequence of definitions and declarations'.  If not, the parser
reports a syntax error.

<div class="node">
<p><hr>
<a name="Grammar-in-Bison"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Semantic-Values">Semantic Values</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Language-and-Grammar">Language and Grammar</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Concepts">Concepts</a>

</div>

<h3 class="section">1.2 From Formal Rules to Bison Input</h3>

<p><a name="index-Bison-grammar-17"></a><a name="index-grammar_002c-Bison-18"></a><a name="index-formal-grammar-19"></a>
A formal grammar is a mathematical construct.  To define the language
for Bison, you must write a file expressing the grammar in Bison syntax:
a <dfn>Bison grammar</dfn> file.  See <a href="#Grammar-File">Bison Grammar Files</a>.

   <p>A nonterminal symbol in the formal grammar is represented in Bison input
as an identifier, like an identifier in C.  By convention, it should be
in lower case, such as <code>expr</code>, <code>stmt</code> or <code>declaration</code>.

   <p>The Bison representation for a terminal symbol is also called a <dfn>token
type</dfn>.  Token types as well can be represented as C-like identifiers.  By
convention, these identifiers should be upper case to distinguish them from
nonterminals: for example, <code>INTEGER</code>, <code>IDENTIFIER</code>, <code>IF</code> or
<code>RETURN</code>.  A terminal symbol that stands for a particular keyword in
the language should be named after that keyword converted to upper case. 
The terminal symbol <code>error</code> is reserved for error recovery. 
See <a href="#Symbols">Symbols</a>.

   <p>A terminal symbol can also be represented as a character literal, just like
a C character constant.  You should do this whenever a token is just a
single character (parenthesis, plus-sign, etc.): use that same character in
a literal as the terminal symbol for that token.

   <p>A third way to represent a terminal symbol is with a C string constant
containing several characters.  See <a href="#Symbols">Symbols</a>, for more information.

   <p>The grammar rules also have an expression in Bison syntax.  For example,
here is the Bison rule for a C <code>return</code> statement.  The semicolon in
quotes is a literal character token, representing part of the C syntax for
the statement; the naked semicolon, and the colon, are Bison punctuation
used in every rule.

<pre class="example">     stmt:   RETURN expr ';'
             ;
</pre>
   <p class="noindent">See <a href="#Rules">Syntax of Grammar Rules</a>.

<div class="node">
<p><hr>
<a name="Semantic-Values"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Semantic-Actions">Semantic Actions</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Grammar-in-Bison">Grammar in Bison</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Concepts">Concepts</a>

</div>

<h3 class="section">1.3 Semantic Values</h3>

<p><a name="index-semantic-value-20"></a><a name="index-value_002c-semantic-21"></a>
A formal grammar selects tokens only by their classifications: for example,
if a rule mentions the terminal symbol `integer constant', it means that
<em>any</em> integer constant is grammatically valid in that position.  The
precise value of the constant is irrelevant to how to parse the input: if
`<samp><span class="samp">x+4</span></samp>' is grammatical then `<samp><span class="samp">x+1</span></samp>' or `<samp><span class="samp">x+3989</span></samp>' is equally
grammatical.

   <p>But the precise value is very important for what the input means once it is
parsed.  A compiler is useless if it fails to distinguish between 4, 1 and
3989 as constants in the program!  Therefore, each token in a Bison grammar
has both a token type and a <dfn>semantic value</dfn>.  See <a href="#Semantics">Defining Language Semantics</a>,
for details.

   <p>The token type is a terminal symbol defined in the grammar, such as
<code>INTEGER</code>, <code>IDENTIFIER</code> or <code>','</code>.  It tells everything
you need to know to decide where the token may validly appear and how to
group it with other tokens.  The grammar rules know nothing about tokens
except their types.

   <p>The semantic value has all the rest of the information about the
meaning of the token, such as the value of an integer, or the name of an
identifier.  (A token such as <code>','</code> which is just punctuation doesn't
need to have any semantic value.)

   <p>For example, an input token might be classified as token type
<code>INTEGER</code> and have the semantic value 4.  Another input token might
have the same token type <code>INTEGER</code> but value 3989.  When a grammar
rule says that <code>INTEGER</code> is allowed, either of these tokens is
acceptable because each is an <code>INTEGER</code>.  When the parser accepts the
token, it keeps track of the token's semantic value.

   <p>Each grouping can also have a semantic value as well as its nonterminal
symbol.  For example, in a calculator, an expression typically has a
semantic value that is a number.  In a compiler for a programming
language, an expression typically has a semantic value that is a tree
structure describing the meaning of the expression.

<div class="node">
<p><hr>
<a name="Semantic-Actions"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#GLR-Parsers">GLR Parsers</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Semantic-Values">Semantic Values</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Concepts">Concepts</a>

</div>

<h3 class="section">1.4 Semantic Actions</h3>

<p><a name="index-semantic-actions-22"></a><a name="index-actions_002c-semantic-23"></a>
In order to be useful, a program must do more than parse input; it must
also produce some output based on the input.  In a Bison grammar, a grammar
rule can have an <dfn>action</dfn> made up of C statements.  Each time the
parser recognizes a match for that rule, the action is executed. 
See <a href="#Actions">Actions</a>.

   <p>Most of the time, the purpose of an action is to compute the semantic value
of the whole construct from the semantic values of its parts.  For example,
suppose we have a rule which says an expression can be the sum of two
expressions.  When the parser recognizes such a sum, each of the
subexpressions has a semantic value which describes how it was built up. 
The action for this rule should create a similar sort of value for the
newly recognized larger expression.

   <p>For example, here is a rule that says an expression can be the sum of
two subexpressions:

<pre class="example">     expr: expr '+' expr   { $$ = $1 + $3; }
             ;
</pre>
   <p class="noindent">The action says how to produce the semantic value of the sum expression
from the values of the two subexpressions.

<div class="node">
<p><hr>
<a name="GLR-Parsers"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Locations-Overview">Locations Overview</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Semantic-Actions">Semantic Actions</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Concepts">Concepts</a>

</div>

<h3 class="section">1.5 Writing <acronym>GLR</acronym> Parsers</h3>

<p><a name="index-g_t_0040acronym_007bGLR_007d-parsing-24"></a><a name="index-generalized-_0040acronym_007bLR_007d-_0028_0040acronym_007bGLR_007d_0029-parsing-25"></a><a name="index-g_t_0025glr_002dparser-26"></a><a name="index-conflicts-27"></a><a name="index-shift_002freduce-conflicts-28"></a>
In some grammars, there will be cases where Bison's standard
<acronym>LALR</acronym>(1) parsing algorithm cannot decide whether to apply a
certain grammar rule at a given point.  That is, it may not be able to
decide (on the basis of the input read so far) which of two possible
reductions (applications of a grammar rule) applies, or whether to apply
a reduction or read more of the input and apply a reduction later in the
input.  These are known respectively as <dfn>reduce/reduce</dfn> conflicts
(see <a href="#Reduce_002fReduce">Reduce/Reduce</a>), and <dfn>shift/reduce</dfn> conflicts
(see <a href="#Shift_002fReduce">Shift/Reduce</a>).

   <p>To use a grammar that is not easily modified to be <acronym>LALR</acronym>(1), a
more general parsing algorithm is sometimes necessary.  If you include
<code>%glr-parser</code> among the Bison declarations in your file
(see <a href="#Grammar-Outline">Grammar Outline</a>), the result will be a Generalized <acronym>LR</acronym>
(<acronym>GLR</acronym>) parser.  These parsers handle Bison grammars that
contain no unresolved conflicts (i.e., after applying precedence
declarations) identically to <acronym>LALR</acronym>(1) parsers.  However, when
faced with unresolved shift/reduce and reduce/reduce conflicts,
<acronym>GLR</acronym> parsers use the simple expedient of doing both,
effectively cloning the parser to follow both possibilities.  Each of
the resulting parsers can again split, so that at any given time, there
can be any number of possible parses being explored.  The parsers
proceed in lockstep; that is, all of them consume (shift) a given input
symbol before any of them proceed to the next.  Each of the cloned
parsers eventually meets one of two possible fates: either it runs into
a parsing error, in which case it simply vanishes, or it merges with
another parser, because the two of them have reduced the input to an
identical set of symbols.

   <p>During the time that there are multiple parsers, semantic actions are
recorded, but not performed.  When a parser disappears, its recorded
semantic actions disappear as well, and are never performed.  When a
reduction makes two parsers identical, causing them to merge, Bison
records both sets of semantic actions.  Whenever the last two parsers
merge, reverting to the single-parser case, Bison resolves all the
outstanding actions either by precedences given to the grammar rules
involved, or by performing both actions, and then calling a designated
user-defined function on the resulting values to produce an arbitrary
merged result.

   <p>Let's consider an example, vastly simplified from a C++ grammar.

<pre class="example">     %{
       #include &lt;stdio.h&gt;
       #define YYSTYPE char const *
       int yylex (void);
       void yyerror (char const *);
     %}
     
     %token TYPENAME ID
     
     %right '='
     %left '+'
     
     %glr-parser
     
     %%
     
     prog :
          | prog stmt   { printf ("\n"); }
          ;
     
     stmt : expr ';'  %dprec 1
          | decl      %dprec 2
          ;
     
     expr : ID               { printf ("%s ", $$); }
          | TYPENAME '(' expr ')'
                             { printf ("%s &lt;cast&gt; ", $1); }
          | expr '+' expr    { printf ("+ "); }
          | expr '=' expr    { printf ("= "); }
          ;
     
     decl : TYPENAME declarator ';'
                             { printf ("%s &lt;declare&gt; ", $1); }
          | TYPENAME declarator '=' expr ';'
                             { printf ("%s &lt;init-declare&gt; ", $1); }
          ;
     
     declarator : ID         { printf ("\"%s\" ", $1); }
          | '(' declarator ')'
          ;
</pre>
   <p class="noindent">This models a problematic part of the C++ grammar&mdash;the ambiguity between
certain declarations and statements.  For example,

<pre class="example">     T (x) = y+z;
</pre>
   <p class="noindent">parses as either an <code>expr</code> or a <code>stmt</code>
(assuming that `<samp><span class="samp">T</span></samp>' is recognized as a <code>TYPENAME</code> and
`<samp><span class="samp">x</span></samp>' as an <code>ID</code>). 
Bison detects this as a reduce/reduce conflict between the rules
<code>expr : ID</code> and <code>declarator : ID</code>, which it cannot resolve at the
time it encounters <code>x</code> in the example above.  The two <code>%dprec</code>
declarations, however, give precedence to interpreting the example as a
<code>decl</code>, which implies that <code>x</code> is a declarator. 
The parser therefore prints

<pre class="example">     "x" y z + T &lt;init-declare&gt;
</pre>
   <p>Consider a different input string for this parser:

<pre class="example">     T (x) + y;
</pre>
   <p class="noindent">Here, there is no ambiguity (this cannot be parsed as a declaration). 
However, at the time the Bison parser encounters <code>x</code>, it does not
have enough information to resolve the reduce/reduce conflict (again,
between <code>x</code> as an <code>expr</code> or a <code>declarator</code>).  In this
case, no precedence declaration is used.  Instead, the parser splits
into two, one assuming that <code>x</code> is an <code>expr</code>, and the other
assuming <code>x</code> is a <code>declarator</code>.  The second of these parsers
then vanishes when it sees <code>+</code>, and the parser prints

<pre class="example">     x T &lt;cast&gt; y +
</pre>
   <p>Suppose that instead of resolving the ambiguity, you wanted to see all
the possibilities.  For this purpose, we must <dfn>merge</dfn> the semantic
actions of the two possible parsers, rather than choosing one over the
other.  To do so, you could change the declaration of <code>stmt</code> as
follows:

<pre class="example">     stmt : expr ';'  %merge &lt;stmtMerge&gt;
          | decl      %merge &lt;stmtMerge&gt;
          ;
</pre>
   <p class="noindent">and define the <code>stmtMerge</code> function as:

<pre class="example">     static YYSTYPE
     stmtMerge (YYSTYPE x0, YYSTYPE x1)
     {
       printf ("&lt;OR&gt; ");
       return "";
     }
</pre>
   <p class="noindent">with an accompanying forward declaration
in the C declarations at the beginning of the file:

<pre class="example">     %{
       #define YYSTYPE char const *
       static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1);
     %}
</pre>
   <p class="noindent">With these declarations, the resulting parser will parse the first example
as both an <code>expr</code> and a <code>decl</code>, and print

<pre class="example">     "x" y z + T &lt;init-declare&gt; x T &lt;cast&gt; y z + = &lt;OR&gt;
</pre>
   <pre class="sp">

</pre>

<a name="index-g_t_0040code_007bincline_007d-29"></a><a name="index-g_t_0040acronym_007bGLR_007d-parsers-and-_0040code_007binline_007d-30"></a>The <acronym>GLR</acronym> parsers require a compiler for <acronym>ISO</acronym> C89 or
later.  In addition, they use the <code>inline</code> keyword, which is not
C89, but is C99 and is a common extension in pre-C99 compilers.  It is
up to the user of these parsers to handle
portability issues.  For instance, if using Autoconf and the Autoconf
macro <code>AC_C_INLINE</code>, a mere

<pre class="example">     %{
       #include &lt;config.h&gt;
     %}
</pre>
   <p class="noindent">will suffice.  Otherwise, we suggest

<pre class="example">     %{
       #if __STDC_VERSION__ &lt; 199901 &amp;&amp; ! defined __GNUC__ &amp;&amp; ! defined inline
        #define inline
       #endif
     %}
</pre>
   <div class="node">
<p><hr>
<a name="Locations-Overview"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Bison-Parser">Bison Parser</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#GLR-Parsers">GLR Parsers</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Concepts">Concepts</a>

</div>

<h3 class="section">1.6 Locations</h3>

<p><a name="index-location-31"></a><a name="index-textual-position-32"></a><a name="index-position_002c-textual-33"></a>
Many applications, like interpreters or compilers, have to produce verbose
and useful error messages.  To achieve this, one must be able to keep track of
the <dfn>textual position</dfn>, or <dfn>location</dfn>, of each syntactic construct. 
Bison provides a mechanism for handling these locations.

   <p>Each token has a semantic value.  In a similar fashion, each token has an
associated location, but the type of locations is the same for all tokens and
groupings.  Moreover, the output parser is equipped with a default data
structure for storing locations (see <a href="#Locations">Locations</a>, for more details).

   <p>Like semantic values, locations can be reached in actions using a dedicated
set of constructs.  In the example above, the location of the whole grouping
is <code>@$</code>, while the locations of the subexpressions are <code>@1</code> and
<code>@3</code>.

   <p>When a rule is matched, a default action is used to compute the semantic value
of its left hand side (see <a href="#Actions">Actions</a>).  In the same way, another default
action is used for locations.  However, the action for locations is general
enough for most cases, meaning there is usually no need to describe for each
rule how <code>@$</code> should be formed.  When building a new location for a given
grouping, the default behavior of the output parser is to take the beginning
of the first symbol, and the end of the last symbol.

<div class="node">
<p><hr>
<a name="Bison-Parser"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Stages">Stages</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Locations-Overview">Locations Overview</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Concepts">Concepts</a>

</div>

<h3 class="section">1.7 Bison Output: the Parser File</h3>

<p><a name="index-Bison-parser-34"></a><a name="index-Bison-utility-35"></a><a name="index-lexical-analyzer_002c-purpose-36"></a><a name="index-parser-37"></a>
When you run Bison, you give it a Bison grammar file as input.  The output
is a C source file that parses the language described by the grammar. 
This file is called a <dfn>Bison parser</dfn>.  Keep in mind that the Bison
utility and the Bison parser are two distinct programs: the Bison utility
is a program whose output is the Bison parser that becomes part of your
program.

   <p>The job of the Bison parser is to group tokens into groupings according to
the grammar rules&mdash;for example, to build identifiers and operators into
expressions.  As it does this, it runs the actions for the grammar rules it
uses.

   <p>The tokens come from a function called the <dfn>lexical analyzer</dfn> that
you must supply in some fashion (such as by writing it in C).  The Bison
parser calls the lexical analyzer each time it wants a new token.  It
doesn't know what is &ldquo;inside&rdquo; the tokens (though their semantic values
may reflect this).  Typically the lexical analyzer makes the tokens by
parsing characters of text, but Bison does not depend on this. 
See <a href="#Lexical">The Lexical Analyzer Function <code>yylex</code></a>.

   <p>The Bison parser file is C code which defines a function named
<code>yyparse</code> which implements that grammar.  This function does not make
a complete C program: you must supply some additional functions.  One is
the lexical analyzer.  Another is an error-reporting function which the
parser calls to report an error.  In addition, a complete C program must
start with a function called <code>main</code>; you have to provide this, and
arrange for it to call <code>yyparse</code> or the parser will never run. 
See <a href="#Interface">Parser C-Language Interface</a>.

   <p>Aside from the token type names and the symbols in the actions you
write, all symbols defined in the Bison parser file itself
begin with `<samp><span class="samp">yy</span></samp>' or `<samp><span class="samp">YY</span></samp>'.  This includes interface functions
such as the lexical analyzer function <code>yylex</code>, the error reporting
function <code>yyerror</code> and the parser function <code>yyparse</code> itself. 
This also includes numerous identifiers used for internal purposes. 
Therefore, you should avoid using C identifiers starting with `<samp><span class="samp">yy</span></samp>'
or `<samp><span class="samp">YY</span></samp>' in the Bison grammar file except for the ones defined in
this manual.

   <p>In some cases the Bison parser file includes system headers, and in
those cases your code should respect the identifiers reserved by those
headers.  On some non-<acronym>GNU</acronym> hosts, <code>&lt;alloca.h&gt;</code>,
<code>&lt;stddef.h&gt;</code>, and <code>&lt;stdlib.h&gt;</code> are included as needed to
declare memory allocators and related types.  Other system headers may
be included if you define <code>YYDEBUG</code> to a nonzero value
(see <a href="#Tracing">Tracing Your Parser</a>).

<div class="node">
<p><hr>
<a name="Stages"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Grammar-Layout">Grammar Layout</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Bison-Parser">Bison Parser</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Concepts">Concepts</a>

</div>

<h3 class="section">1.8 Stages in Using Bison</h3>

<p><a name="index-stages-in-using-Bison-38"></a><a name="index-using-Bison-39"></a>
The actual language-design process using Bison, from grammar specification
to a working compiler or interpreter, has these parts:

     <ol type=1 start=1>
<li>Formally specify the grammar in a form recognized by Bison
(see <a href="#Grammar-File">Bison Grammar Files</a>).  For each grammatical rule
in the language, describe the action that is to be taken when an
instance of that rule is recognized.  The action is described by a
sequence of C statements.

     <li>Write a lexical analyzer to process input and pass tokens to the parser. 
The lexical analyzer may be written by hand in C (see <a href="#Lexical">The Lexical Analyzer Function <code>yylex</code></a>).  It could also be produced
using Lex, but the use of Lex is not discussed in this manual.

     <li>Write a controlling function that calls the Bison-produced parser.

     <li>Write error-reporting routines.
        </ol>

   <p>To turn this source code as written into a runnable program, you
must follow these steps:

     <ol type=1 start=1>
<li>Run Bison on the grammar to produce the parser.

     <li>Compile the code output by Bison, as well as any other source files.

     <li>Link the object files to produce the finished product.
        </ol>

<div class="node">
<p><hr>
<a name="Grammar-Layout"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Stages">Stages</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Concepts">Concepts</a>

</div>

<h3 class="section">1.9 The Overall Layout of a Bison Grammar</h3>

<p><a name="index-grammar-file-40"></a><a name="index-file-format-41"></a><a name="index-format-of-grammar-file-42"></a><a name="index-layout-of-Bison-grammar-43"></a>
The input file for the Bison utility is a <dfn>Bison grammar file</dfn>.  The
general form of a Bison grammar file is as follows:

<pre class="example">     %{
     <var>Prologue</var>
     %}
     
     <var>Bison declarations</var>
     
     %%
     <var>Grammar rules</var>
     %%
     <var>Epilogue</var>
</pre>
   <p class="noindent">The `<samp><span class="samp">%%</span></samp>', `<samp><span class="samp">%{</span></samp>' and `<samp><span class="samp">%}</span></samp>' are punctuation that appears
in every Bison grammar file to separate the sections.

   <p>The prologue may define types and variables used in the actions.  You can
also use preprocessor commands to define macros used there, and use
<code>#include</code> to include header files that do any of these things. 
You need to declare the lexical analyzer <code>yylex</code> and the error
printer <code>yyerror</code> here, along with any other global identifiers
used by the actions in the grammar rules.

   <p>The Bison declarations declare the names of the terminal and nonterminal
symbols, and may also describe operator precedence and the data types of
semantic values of various symbols.

   <p>The grammar rules define how to construct each nonterminal symbol from its
parts.

   <p>The epilogue can contain any code you want to use.  Often the
definitions of functions declared in the prologue go here.  In a
simple program, all the rest of the program can go here.

<div class="node">
<p><hr>
<a name="Examples"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Grammar-File">Grammar File</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Concepts">Concepts</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="chapter">2 Examples</h2>

<p><a name="index-simple-examples-44"></a><a name="index-examples_002c-simple-45"></a>
Now we show and explain three sample programs written using Bison: a
reverse polish notation calculator, an algebraic (infix) notation
calculator, and a multi-function calculator.  All three have been tested
under BSD Unix 4.3; each produces a usable, though limited, interactive
desk-top calculator.

   <p>These examples are simple, but Bison grammars for real programming
languages are written the same way.

<ul class="menu">
<li><a accesskey="1" href="#RPN-Calc">RPN Calc</a>:           Reverse polish notation calculator;
                        a first example with no operator precedence. 
<li><a accesskey="2" href="#Infix-Calc">Infix Calc</a>:         Infix (algebraic) notation calculator. 
                        Operator precedence is introduced. 
<li><a accesskey="3" href="#Simple-Error-Recovery">Simple Error Recovery</a>:   Continuing after syntax errors. 
<li><a accesskey="4" href="#Location-Tracking-Calc">Location Tracking Calc</a>:  Demonstrating the use of @<var>n</var> and @$. 
<li><a accesskey="5" href="#Multi_002dfunction-Calc">Multi-function Calc</a>:   Calculator with memory and trig functions. 
                           It uses multiple data-types for semantic values. 
<li><a accesskey="6" href="#Exercises">Exercises</a>:          Ideas for improving the multi-function calculator. 
</ul>

<div class="node">
<p><hr>
<a name="RPN-Calc"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Infix-Calc">Infix Calc</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Examples">Examples</a>

</div>

<h3 class="section">2.1 Reverse Polish Notation Calculator</h3>

<p><a name="index-reverse-polish-notation-46"></a><a name="index-polish-notation-calculator-47"></a><a name="index-g_t_0040code_007brpcalc_007d-48"></a><a name="index-calculator_002c-simple-49"></a>
The first example is that of a simple double-precision <dfn>reverse polish
notation</dfn> calculator (a calculator using postfix operators).  This example
provides a good starting point, since operator precedence is not an issue. 
The second example will illustrate how operator precedence is handled.

   <p>The source code for this calculator is named <samp><span class="file">rpcalc.y</span></samp>.  The
`<samp><span class="samp">.y</span></samp>' extension is a convention used for Bison input files.

<ul class="menu">
<li><a accesskey="1" href="#Rpcalc-Decls">Decls</a>:   Prologue (declarations) for rpcalc. 
<li><a accesskey="2" href="#Rpcalc-Rules">Rules</a>:   Grammar Rules for rpcalc, with explanation. 
<li><a accesskey="3" href="#Rpcalc-Lexer">Lexer</a>:   The lexical analyzer. 
<li><a accesskey="4" href="#Rpcalc-Main">Main</a>:     The controlling function. 
<li><a accesskey="5" href="#Rpcalc-Error">Error</a>:   The error reporting function. 
<li><a accesskey="6" href="#Rpcalc-Gen">Gen</a>:       Running Bison on the grammar file. 
<li><a accesskey="7" href="#Rpcalc-Compile">Comp</a>:  Run the C compiler on the output code. 
</ul>

<div class="node">
<p><hr>
<a name="Rpcalc-Decls"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Rpcalc-Rules">Rpcalc Rules</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#RPN-Calc">RPN Calc</a>

</div>

<h4 class="subsection">2.1.1 Declarations for <code>rpcalc</code></h4>

<p>Here are the C and Bison declarations for the reverse polish notation
calculator.  As in C, comments are placed between `<samp><span class="samp">/*...*/</span></samp>'.

<pre class="example">     /* Reverse polish notation calculator.  */
     
     %{
       #define YYSTYPE double
       #include &lt;math.h&gt;
       int yylex (void);
       void yyerror (char const *);
     %}
     
     %token NUM
     
     %% /* Grammar rules and actions follow.  */
</pre>
   <p>The declarations section (see <a href="#Prologue">The prologue</a>) contains two
preprocessor directives and two forward declarations.

   <p>The <code>#define</code> directive defines the macro <code>YYSTYPE</code>, thus
specifying the C data type for semantic values of both tokens and
groupings (see <a href="#Value-Type">Data Types of Semantic Values</a>).  The
Bison parser will use whatever type <code>YYSTYPE</code> is defined as; if you
don't define it, <code>int</code> is the default.  Because we specify
<code>double</code>, each token and each expression has an associated value,
which is a floating point number.

   <p>The <code>#include</code> directive is used to declare the exponentiation
function <code>pow</code>.

   <p>The forward declarations for <code>yylex</code> and <code>yyerror</code> are
needed because the C language requires that functions be declared
before they are used.  These functions will be defined in the
epilogue, but the parser calls them so they must be declared in the
prologue.

   <p>The second section, Bison declarations, provides information to Bison
about the token types (see <a href="#Bison-Declarations">The Bison Declarations Section</a>).  Each terminal symbol that is not a
single-character literal must be declared here.  (Single-character
literals normally don't need to be declared.)  In this example, all the
arithmetic operators are designated by single-character literals, so the
only terminal symbol that needs to be declared is <code>NUM</code>, the token
type for numeric constants.

<div class="node">
<p><hr>
<a name="Rpcalc-Rules"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Rpcalc-Lexer">Rpcalc Lexer</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Rpcalc-Decls">Rpcalc Decls</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#RPN-Calc">RPN Calc</a>

</div>

<h4 class="subsection">2.1.2 Grammar Rules for <code>rpcalc</code></h4>

<p>Here are the grammar rules for the reverse polish notation calculator.

<pre class="example">     input:    /* empty */
             | input line
     ;
     
     line:     '\n'
             | exp '\n'      { printf ("\t%.10g\n", $1); }
     ;
     
     exp:      NUM           { $$ = $1;           }
             | exp exp '+'   { $$ = $1 + $2;      }
             | exp exp '-'   { $$ = $1 - $2;      }
             | exp exp '*'   { $$ = $1 * $2;      }
             | exp exp '/'   { $$ = $1 / $2;      }
              /* Exponentiation */
             | exp exp '^'   { $$ = pow ($1, $2); }
              /* Unary minus    */
             | exp 'n'       { $$ = -$1;          }
     ;
     %%
</pre>
   <p>The groupings of the rpcalc &ldquo;language&rdquo; defined here are the expression
(given the name <code>exp</code>), the line of input (<code>line</code>), and the
complete input transcript (<code>input</code>).  Each of these nonterminal
symbols has several alternate rules, joined by the `<samp><span class="samp">|</span></samp>' punctuator
which is read as &ldquo;or&rdquo;.  The following sections explain what these rules
mean.

   <p>The semantics of the language is determined by the actions taken when a
grouping is recognized.  The actions are the C code that appears inside
braces.  See <a href="#Actions">Actions</a>.

   <p>You must specify these actions in C, but Bison provides the means for
passing semantic values between the rules.  In each action, the
pseudo-variable <code>$$</code> stands for the semantic value for the grouping
that the rule is going to construct.  Assigning a value to <code>$$</code> is the
main job of most actions.  The semantic values of the components of the
rule are referred to as <code>$1</code>, <code>$2</code>, and so on.

<ul class="menu">
<li><a accesskey="1" href="#Rpcalc-Input">Rpcalc Input</a>
<li><a accesskey="2" href="#Rpcalc-Line">Rpcalc Line</a>
<li><a accesskey="3" href="#Rpcalc-Expr">Rpcalc Expr</a>
</ul>

<div class="node">
<p><hr>
<a name="Rpcalc-Input"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Rpcalc-Line">Rpcalc Line</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Rpcalc-Rules">Rpcalc Rules</a>

</div>

<h5 class="subsubsection">2.1.2.1 Explanation of <code>input</code></h5>

<p>Consider the definition of <code>input</code>:

<pre class="example">     input:    /* empty */
             | input line
     ;
</pre>
   <p>This definition reads as follows: &ldquo;A complete input is either an empty
string, or a complete input followed by an input line&rdquo;.  Notice that
&ldquo;complete input&rdquo; is defined in terms of itself.  This definition is said
to be <dfn>left recursive</dfn> since <code>input</code> appears always as the
leftmost symbol in the sequence.  See <a href="#Recursion">Recursive Rules</a>.

   <p>The first alternative is empty because there are no symbols between the
colon and the first `<samp><span class="samp">|</span></samp>'; this means that <code>input</code> can match an
empty string of input (no tokens).  We write the rules this way because it
is legitimate to type <kbd>Ctrl-d</kbd> right after you start the calculator. 
It's conventional to put an empty alternative first and write the comment
`<samp><span class="samp">/* empty */</span></samp>' in it.

   <p>The second alternate rule (<code>input line</code>) handles all nontrivial input. 
It means, &ldquo;After reading any number of lines, read one more line if
possible.&rdquo;  The left recursion makes this rule into a loop.  Since the
first alternative matches empty input, the loop can be executed zero or
more times.

   <p>The parser function <code>yyparse</code> continues to process input until a
grammatical error is seen or the lexical analyzer says there are no more
input tokens; we will arrange for the latter to happen at end-of-input.

<div class="node">
<p><hr>
<a name="Rpcalc-Line"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Rpcalc-Expr">Rpcalc Expr</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Rpcalc-Input">Rpcalc Input</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Rpcalc-Rules">Rpcalc Rules</a>

</div>

<h5 class="subsubsection">2.1.2.2 Explanation of <code>line</code></h5>

<p>Now consider the definition of <code>line</code>:

<pre class="example">     line:     '\n'
             | exp '\n'  { printf ("\t%.10g\n", $1); }
     ;
</pre>
   <p>The first alternative is a token which is a newline character; this means
that rpcalc accepts a blank line (and ignores it, since there is no
action).  The second alternative is an expression followed by a newline. 
This is the alternative that makes rpcalc useful.  The semantic value of
the <code>exp</code> grouping is the value of <code>$1</code> because the <code>exp</code> in
question is the first symbol in the alternative.  The action prints this
value, which is the result of the computation the user asked for.

   <p>This action is unusual because it does not assign a value to <code>$$</code>.  As
a consequence, the semantic value associated with the <code>line</code> is
uninitialized (its value will be unpredictable).  This would be a bug if
that value were ever used, but we don't use it: once rpcalc has printed the
value of the user's input line, that value is no longer needed.

<div class="node">
<p><hr>
<a name="Rpcalc-Expr"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Rpcalc-Line">Rpcalc Line</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Rpcalc-Rules">Rpcalc Rules</a>

</div>

<h5 class="subsubsection">2.1.2.3 Explanation of <code>expr</code></h5>

<p>The <code>exp</code> grouping has several rules, one for each kind of expression. 
The first rule handles the simplest expressions: those that are just numbers. 
The second handles an addition-expression, which looks like two expressions
followed by a plus-sign.  The third handles subtraction, and so on.

<pre class="example">     exp:      NUM
             | exp exp '+'     { $$ = $1 + $2;    }
             | exp exp '-'     { $$ = $1 - $2;    }
             ...
             ;
</pre>
   <p>We have used `<samp><span class="samp">|</span></samp>' to join all the rules for <code>exp</code>, but we could
equally well have written them separately:

<pre class="example">     exp:      NUM ;
     exp:      exp exp '+'     { $$ = $1 + $2;    } ;
     exp:      exp exp '-'     { $$ = $1 - $2;    } ;
             ...
</pre>
   <p>Most of the rules have actions that compute the value of the expression in
terms of the value of its parts.  For example, in the rule for addition,
<code>$1</code> refers to the first component <code>exp</code> and <code>$2</code> refers to
the second one.  The third component, <code>'+'</code>, has no meaningful
associated semantic value, but if it had one you could refer to it as
<code>$3</code>.  When <code>yyparse</code> recognizes a sum expression using this
rule, the sum of the two subexpressions' values is produced as the value of
the entire expression.  See <a href="#Actions">Actions</a>.

   <p>You don't have to give an action for every rule.  When a rule has no
action, Bison by default copies the value of <code>$1</code> into <code>$$</code>. 
This is what happens in the first rule (the one that uses <code>NUM</code>).

   <p>The formatting shown here is the recommended convention, but Bison does
not require it.  You can add or change white space as much as you wish. 
For example, this:

<pre class="example">     exp   : NUM | exp exp '+' {$$ = $1 + $2; } | ...
</pre>
   <p class="noindent">means the same thing as this:

<pre class="example">     exp:      NUM
             | exp exp '+'    { $$ = $1 + $2; }
             | ...
</pre>
   <p class="noindent">The latter, however, is much more readable.

<div class="node">
<p><hr>
<a name="Rpcalc-Lexer"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Rpcalc-Main">Rpcalc Main</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Rpcalc-Rules">Rpcalc Rules</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#RPN-Calc">RPN Calc</a>

</div>

<h4 class="subsection">2.1.3 The <code>rpcalc</code> Lexical Analyzer</h4>

<p><a name="index-writing-a-lexical-analyzer-50"></a><a name="index-lexical-analyzer_002c-writing-51"></a>
The lexical analyzer's job is low-level parsing: converting characters
or sequences of characters into tokens.  The Bison parser gets its
tokens by calling the lexical analyzer.  See <a href="#Lexical">The Lexical Analyzer Function <code>yylex</code></a>.

   <p>Only a simple lexical analyzer is needed for the <acronym>RPN</acronym>
calculator.  This
lexical analyzer skips blanks and tabs, then reads in numbers as
<code>double</code> and returns them as <code>NUM</code> tokens.  Any other character
that isn't part of a number is a separate token.  Note that the token-code
for such a single-character token is the character itself.

   <p>The return value of the lexical analyzer function is a numeric code which
represents a token type.  The same text used in Bison rules to stand for
this token type is also a C expression for the numeric code for the type. 
This works in two ways.  If the token type is a character literal, then its
numeric code is that of the character; you can use the same
character literal in the lexical analyzer to express the number.  If the
token type is an identifier, that identifier is defined by Bison as a C
macro whose definition is the appropriate number.  In this example,
therefore, <code>NUM</code> becomes a macro for <code>yylex</code> to use.

   <p>The semantic value of the token (if it has one) is stored into the
global variable <code>yylval</code>, which is where the Bison parser will look
for it.  (The C data type of <code>yylval</code> is <code>YYSTYPE</code>, which was
defined at the beginning of the grammar; see <a href="#Rpcalc-Decls">Declarations for <code>rpcalc</code></a>.)

   <p>A token type code of zero is returned if the end-of-input is encountered. 
(Bison recognizes any nonpositive value as indicating end-of-input.)

   <p>Here is the code for the lexical analyzer:

<pre class="example">     /* The lexical analyzer returns a double floating point
        number on the stack and the token NUM, or the numeric code
        of the character read if not a number.  It skips all blanks
        and tabs, and returns 0 for end-of-input.  */
     
     #include &lt;ctype.h&gt;
     
     int
     yylex (void)
     {
       int c;
     
       /* Skip white space.  */
       while ((c = getchar ()) == ' ' || c == '\t')
         ;
       /* Process numbers.  */
       if (c == '.' || isdigit (c))
         {
           ungetc (c, stdin);
           scanf ("%lf", &amp;yylval);
           return NUM;
         }
       /* Return end-of-input.  */
       if (c == EOF)
         return 0;
       /* Return a single char.  */
       return c;
     }
</pre>
   <div class="node">
<p><hr>
<a name="Rpcalc-Main"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Rpcalc-Error">Rpcalc Error</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Rpcalc-Lexer">Rpcalc Lexer</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#RPN-Calc">RPN Calc</a>

</div>

<h4 class="subsection">2.1.4 The Controlling Function</h4>

<p><a name="index-controlling-function-52"></a><a name="index-main-function-in-simple-example-53"></a>
In keeping with the spirit of this example, the controlling function is
kept to the bare minimum.  The only requirement is that it call
<code>yyparse</code> to start the process of parsing.

<pre class="example">     int
     main (void)
     {
       return yyparse ();
     }
</pre>
   <div class="node">
<p><hr>
<a name="Rpcalc-Error"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Rpcalc-Gen">Rpcalc Gen</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Rpcalc-Main">Rpcalc Main</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#RPN-Calc">RPN Calc</a>

</div>

<h4 class="subsection">2.1.5 The Error Reporting Routine</h4>

<p><a name="index-error-reporting-routine-54"></a>
When <code>yyparse</code> detects a syntax error, it calls the error reporting
function <code>yyerror</code> to print an error message (usually but not
always <code>"syntax error"</code>).  It is up to the programmer to supply
<code>yyerror</code> (see <a href="#Interface">Parser C-Language Interface</a>), so
here is the definition we will use:

<pre class="example">     #include &lt;stdio.h&gt;
     
     /* Called by yyparse on error.  */
     void
     yyerror (char const *s)
     {
       printf ("%s\n", s);
     }
</pre>
   <p>After <code>yyerror</code> returns, the Bison parser may recover from the error
and continue parsing if the grammar contains a suitable error rule
(see <a href="#Error-Recovery">Error Recovery</a>).  Otherwise, <code>yyparse</code> returns nonzero.  We
have not written any error rules in this example, so any invalid input will
cause the calculator program to exit.  This is not clean behavior for a
real calculator, but it is adequate for the first example.

<div class="node">
<p><hr>
<a name="Rpcalc-Gen"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Rpcalc-Compile">Rpcalc Compile</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Rpcalc-Error">Rpcalc Error</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#RPN-Calc">RPN Calc</a>

</div>

<h4 class="subsection">2.1.6 Running Bison to Make the Parser</h4>

<p><a name="index-running-Bison-_0028introduction_0029-55"></a>
Before running Bison to produce a parser, we need to decide how to
arrange all the source code in one or more source files.  For such a
simple example, the easiest thing is to put everything in one file.  The
definitions of <code>yylex</code>, <code>yyerror</code> and <code>main</code> go at the
end, in the epilogue of the file
(see <a href="#Grammar-Layout">The Overall Layout of a Bison Grammar</a>).

   <p>For a large project, you would probably have several source files, and use
<code>make</code> to arrange to recompile them.

   <p>With all the source in a single file, you use the following command to
convert it into a parser file:

<pre class="example">     bison <var>file_name</var>.y
</pre>
   <p class="noindent">In this example the file was called <samp><span class="file">rpcalc.y</span></samp> (for &ldquo;Reverse Polish
<span class="sc">calc</span>ulator&rdquo;).  Bison produces a file named <samp><var>file_name</var><span class="file">.tab.c</span></samp>,
removing the `<samp><span class="samp">.y</span></samp>' from the original file name.  The file output by
Bison contains the source code for <code>yyparse</code>.  The additional
functions in the input file (<code>yylex</code>, <code>yyerror</code> and <code>main</code>)
are copied verbatim to the output.

<div class="node">
<p><hr>
<a name="Rpcalc-Compile"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Rpcalc-Gen">Rpcalc Gen</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#RPN-Calc">RPN Calc</a>

</div>

<h4 class="subsection">2.1.7 Compiling the Parser File</h4>

<p><a name="index-compiling-the-parser-56"></a>
Here is how to compile and run the parser file:

<pre class="example">     # <span class="roman">List files in current directory.</span>
     $ <kbd>ls</kbd>
     rpcalc.tab.c  rpcalc.y
     
     # <span class="roman">Compile the Bison parser.</span>
     # <span class="roman">`<samp>-lm</samp>' tells compiler to search math library for </span><code>pow</code><span class="roman">.</span>
     $ <kbd>cc -lm -o rpcalc rpcalc.tab.c</kbd>
     
     # <span class="roman">List files again.</span>
     $ <kbd>ls</kbd>
     rpcalc  rpcalc.tab.c  rpcalc.y
</pre>
   <p>The file <samp><span class="file">rpcalc</span></samp> now contains the executable code.  Here is an
example session using <code>rpcalc</code>.

<pre class="example">     $ <kbd>rpcalc</kbd>
     <kbd>4 9 +</kbd>
     13
     <kbd>3 7 + 3 4 5 *+-</kbd>
     -13
     <kbd>3 7 + 3 4 5 * + - n</kbd>              <span class="roman">Note the unary minus, `<samp>n</samp>'</span>
     13
     <kbd>5 6 / 4 n +</kbd>
     -3.166666667
     <kbd>3 4 ^</kbd>                            <span class="roman">Exponentiation</span>
     81
     <kbd>^D</kbd>                               <span class="roman">End-of-file indicator</span>
     $
</pre>
   <div class="node">
<p><hr>
<a name="Infix-Calc"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Simple-Error-Recovery">Simple Error Recovery</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#RPN-Calc">RPN Calc</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Examples">Examples</a>

</div>

<h3 class="section">2.2 Infix Notation Calculator: <code>calc</code></h3>

<p><a name="index-infix-notation-calculator-57"></a><a name="index-g_t_0040code_007bcalc_007d-58"></a><a name="index-calculator_002c-infix-notation-59"></a>
We now modify rpcalc to handle infix operators instead of postfix.  Infix
notation involves the concept of operator precedence and the need for
parentheses nested to arbitrary depth.  Here is the Bison code for
<samp><span class="file">calc.y</span></samp>, an infix desk-top calculator.

<pre class="example">     /* Infix notation calculator.  */
     
     %{
       #define YYSTYPE double
       #include &lt;math.h&gt;
       #include &lt;stdio.h&gt;
       int yylex (void);
       void yyerror (char const *);
     %}
     
     /* Bison declarations.  */
     %token NUM
     %left '-' '+'
     %left '*' '/'
     %left NEG     /* negation--unary minus */
     %right '^'    /* exponentiation */
     
     %% /* The grammar follows.  */
     input:    /* empty */
             | input line
     ;
     
     line:     '\n'
             | exp '\n'  { printf ("\t%.10g\n", $1); }
     ;
     
     exp:      NUM                { $$ = $1;         }
             | exp '+' exp        { $$ = $1 + $3;    }
             | exp '-' exp        { $$ = $1 - $3;    }
             | exp '*' exp        { $$ = $1 * $3;    }
             | exp '/' exp        { $$ = $1 / $3;    }
             | '-' exp  %prec NEG { $$ = -$2;        }
             | exp '^' exp        { $$ = pow ($1, $3); }
             | '(' exp ')'        { $$ = $2;         }
     ;
     %%
</pre>
   <p class="noindent">The functions <code>yylex</code>, <code>yyerror</code> and <code>main</code> can be the
same as before.

   <p>There are two important new features shown in this code.

   <p>In the second section (Bison declarations), <code>%left</code> declares token
types and says they are left-associative operators.  The declarations
<code>%left</code> and <code>%right</code> (right associativity) take the place of
<code>%token</code> which is used to declare a token type name without
associativity.  (These tokens are single-character literals, which
ordinarily don't need to be declared.  We declare them here to specify
the associativity.)

   <p>Operator precedence is determined by the line ordering of the
declarations; the higher the line number of the declaration (lower on
the page or screen), the higher the precedence.  Hence, exponentiation
has the highest precedence, unary minus (<code>NEG</code>) is next, followed
by `<samp><span class="samp">*</span></samp>' and `<samp><span class="samp">/</span></samp>', and so on.  See <a href="#Precedence">Operator Precedence</a>.

   <p>The other important new feature is the <code>%prec</code> in the grammar
section for the unary minus operator.  The <code>%prec</code> simply instructs
Bison that the rule `<samp><span class="samp">| '-' exp</span></samp>' has the same precedence as
<code>NEG</code>&mdash;in this case the next-to-highest.  See <a href="#Contextual-Precedence">Context-Dependent Precedence</a>.

   <p>Here is a sample run of <samp><span class="file">calc.y</span></samp>:

<pre class="example">     $ <kbd>calc</kbd>
     <kbd>4 + 4.5 - (34/(8*3+-3))</kbd>
     6.880952381
     <kbd>-56 + 2</kbd>
     -54
     <kbd>3 ^ 2</kbd>
     9
</pre>
   <div class="node">
<p><hr>
<a name="Simple-Error-Recovery"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Location-Tracking-Calc">Location Tracking Calc</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Infix-Calc">Infix Calc</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Examples">Examples</a>

</div>

<h3 class="section">2.3 Simple Error Recovery</h3>

<p><a name="index-error-recovery_002c-simple-60"></a>
Up to this point, this manual has not addressed the issue of <dfn>error
recovery</dfn>&mdash;how to continue parsing after the parser detects a syntax
error.  All we have handled is error reporting with <code>yyerror</code>. 
Recall that by default <code>yyparse</code> returns after calling
<code>yyerror</code>.  This means that an erroneous input line causes the
calculator program to exit.  Now we show how to rectify this deficiency.

   <p>The Bison language itself includes the reserved word <code>error</code>, which
may be included in the grammar rules.  In the example below it has
been added to one of the alternatives for <code>line</code>:

<pre class="example">     line:     '\n'
             | exp '\n'   { printf ("\t%.10g\n", $1); }
             | error '\n' { yyerrok;                  }
     ;
</pre>
   <p>This addition to the grammar allows for simple error recovery in the
event of a syntax error.  If an expression that cannot be evaluated is
read, the error will be recognized by the third rule for <code>line</code>,
and parsing will continue.  (The <code>yyerror</code> function is still called
upon to print its message as well.)  The action executes the statement
<code>yyerrok</code>, a macro defined automatically by Bison; its meaning is
that error recovery is complete (see <a href="#Error-Recovery">Error Recovery</a>).  Note the
difference between <code>yyerrok</code> and <code>yyerror</code>; neither one is a
misprint.

   <p>This form of error recovery deals with syntax errors.  There are other
kinds of errors; for example, division by zero, which raises an exception
signal that is normally fatal.  A real calculator program must handle this
signal and use <code>longjmp</code> to return to <code>main</code> and resume parsing
input lines; it would also have to discard the rest of the current line of
input.  We won't discuss this issue further because it is not specific to
Bison programs.

<div class="node">
<p><hr>
<a name="Location-Tracking-Calc"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Multi_002dfunction-Calc">Multi-function Calc</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Simple-Error-Recovery">Simple Error Recovery</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Examples">Examples</a>

</div>

<h3 class="section">2.4 Location Tracking Calculator: <code>ltcalc</code></h3>

<p><a name="index-location-tracking-calculator-61"></a><a name="index-g_t_0040code_007bltcalc_007d-62"></a><a name="index-calculator_002c-location-tracking-63"></a>
This example extends the infix notation calculator with location
tracking.  This feature will be used to improve the error messages.  For
the sake of clarity, this example is a simple integer calculator, since
most of the work needed to use locations will be done in the lexical
analyzer.

<ul class="menu">
<li><a accesskey="1" href="#Ltcalc-Decls">Decls</a>:   Bison and C declarations for ltcalc. 
<li><a accesskey="2" href="#Ltcalc-Rules">Rules</a>:   Grammar rules for ltcalc, with explanations. 
<li><a accesskey="3" href="#Ltcalc-Lexer">Lexer</a>:   The lexical analyzer. 
</ul>

<div class="node">
<p><hr>
<a name="Ltcalc-Decls"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Ltcalc-Rules">Ltcalc Rules</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Location-Tracking-Calc">Location Tracking Calc</a>

</div>

<h4 class="subsection">2.4.1 Declarations for <code>ltcalc</code></h4>

<p>The C and Bison declarations for the location tracking calculator are
the same as the declarations for the infix notation calculator.

<pre class="example">     /* Location tracking calculator.  */
     
     %{
       #define YYSTYPE int
       #include &lt;math.h&gt;
       int yylex (void);
       void yyerror (char const *);
     %}
     
     /* Bison declarations.  */
     %token NUM
     
     %left '-' '+'
     %left '*' '/'
     %left NEG
     %right '^'
     
     %% /* The grammar follows.  */
</pre>
   <p class="noindent">Note there are no declarations specific to locations.  Defining a data
type for storing locations is not needed: we will use the type provided
by default (see <a href="#Location-Type">Data Types of Locations</a>), which is a
four member structure with the following integer fields:
<code>first_line</code>, <code>first_column</code>, <code>last_line</code> and
<code>last_column</code>.

<div class="node">
<p><hr>
<a name="Ltcalc-Rules"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Ltcalc-Lexer">Ltcalc Lexer</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Ltcalc-Decls">Ltcalc Decls</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Location-Tracking-Calc">Location Tracking Calc</a>

</div>

<h4 class="subsection">2.4.2 Grammar Rules for <code>ltcalc</code></h4>

<p>Whether handling locations or not has no effect on the syntax of your
language.  Therefore, grammar rules for this example will be very close
to those of the previous example: we will only modify them to benefit
from the new information.

   <p>Here, we will use locations to report divisions by zero, and locate the
wrong expressions or subexpressions.

<pre class="example">     input   : /* empty */
             | input line
     ;
     
     line    : '\n'
             | exp '\n' { printf ("%d\n", $1); }
     ;
     
     exp     : NUM           { $$ = $1; }
             | exp '+' exp   { $$ = $1 + $3; }
             | exp '-' exp   { $$ = $1 - $3; }
             | exp '*' exp   { $$ = $1 * $3; }
             | exp '/' exp
                 {
                   if ($3)
                     $$ = $1 / $3;
                   else
                     {
                       $$ = 1;
                       fprintf (stderr, "%d.%d-%d.%d: division by zero",
                                @3.first_line, @3.first_column,
                                @3.last_line, @3.last_column);
                     }
                 }
             | '-' exp %preg NEG     { $$ = -$2; }
             | exp '^' exp           { $$ = pow ($1, $3); }
             | '(' exp ')'           { $$ = $2; }
</pre>
   <p>This code shows how to reach locations inside of semantic actions, by
using the pseudo-variables <code>@</code><var>n</var> for rule components, and the
pseudo-variable <code>@$</code> for groupings.

   <p>We don't need to assign a value to <code>@$</code>: the output parser does it
automatically.  By default, before executing the C code of each action,
<code>@$</code> is set to range from the beginning of <code>@1</code> to the end
of <code>@</code><var>n</var>, for a rule with <var>n</var> components.  This behavior
can be redefined (see <a href="#Location-Default-Action">Default Action for Locations</a>), and for very specific rules, <code>@$</code> can be computed by
hand.

<div class="node">
<p><hr>
<a name="Ltcalc-Lexer"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Ltcalc-Rules">Ltcalc Rules</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Location-Tracking-Calc">Location Tracking Calc</a>

</div>

<h4 class="subsection">2.4.3 The <code>ltcalc</code> Lexical Analyzer.</h4>

<p>Until now, we relied on Bison's defaults to enable location
tracking.  The next step is to rewrite the lexical analyzer, and make it
able to feed the parser with the token locations, as it already does for
semantic values.

   <p>To this end, we must take into account every single character of the
input text, to avoid the computed locations of being fuzzy or wrong:

<pre class="example">     int
     yylex (void)
     {
       int c;
     
       /* Skip white space.  */
       while ((c = getchar ()) == ' ' || c == '\t')
         ++yylloc.last_column;
     
       /* Step.  */
       yylloc.first_line = yylloc.last_line;
       yylloc.first_column = yylloc.last_column;
     
       /* Process numbers.  */
       if (isdigit (c))
         {
           yylval = c - '0';
           ++yylloc.last_column;
           while (isdigit (c = getchar ()))
             {
               ++yylloc.last_column;
               yylval = yylval * 10 + c - '0';
             }
           ungetc (c, stdin);
           return NUM;
         }
     
       /* Return end-of-input.  */
       if (c == EOF)
         return 0;
     
       /* Return a single char, and update location.  */
       if (c == '\n')
         {
           ++yylloc.last_line;
           yylloc.last_column = 0;
         }
       else
         ++yylloc.last_column;
       return c;
     }
</pre>
   <p>Basically, the lexical analyzer performs the same processing as before:
it skips blanks and tabs, and reads numbers or single-character tokens. 
In addition, it updates <code>yylloc</code>, the global variable (of type
<code>YYLTYPE</code>) containing the token's location.

   <p>Now, each time this function returns a token, the parser has its number
as well as its semantic value, and its location in the text.  The last
needed change is to initialize <code>yylloc</code>, for example in the
controlling function:

<pre class="example">     int
     main (void)
     {
       yylloc.first_line = yylloc.last_line = 1;
       yylloc.first_column = yylloc.last_column = 0;
       return yyparse ();
     }
</pre>
   <p>Remember that computing locations is not a matter of syntax.  Every
character must be associated to a location update, whether it is in
valid input, in comments, in literal strings, and so on.

<div class="node">
<p><hr>
<a name="Multi-function-Calc"></a>
<a name="Multi_002dfunction-Calc"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Exercises">Exercises</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Location-Tracking-Calc">Location Tracking Calc</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Examples">Examples</a>

</div>

<h3 class="section">2.5 Multi-Function Calculator: <code>mfcalc</code></h3>

<p><a name="index-multi_002dfunction-calculator-64"></a><a name="index-g_t_0040code_007bmfcalc_007d-65"></a><a name="index-calculator_002c-multi_002dfunction-66"></a>
Now that the basics of Bison have been discussed, it is time to move on to
a more advanced problem.  The above calculators provided only five
functions, `<samp><span class="samp">+</span></samp>', `<samp><span class="samp">-</span></samp>', `<samp><span class="samp">*</span></samp>', `<samp><span class="samp">/</span></samp>' and `<samp><span class="samp">^</span></samp>'.  It would
be nice to have a calculator that provides other mathematical functions such
as <code>sin</code>, <code>cos</code>, etc.

   <p>It is easy to add new operators to the infix calculator as long as they are
only single-character literals.  The lexical analyzer <code>yylex</code> passes
back all nonnumber characters as tokens, so new grammar rules suffice for
adding a new operator.  But we want something more flexible: built-in
functions whose syntax has this form:

<pre class="example">     <var>function_name</var> (<var>argument</var>)
</pre>
   <p class="noindent">At the same time, we will add memory to the calculator, by allowing you
to create named variables, store values in them, and use them later. 
Here is a sample session with the multi-function calculator:

<pre class="example">     $ <kbd>mfcalc</kbd>
     <kbd>pi = 3.141592653589</kbd>
     3.1415926536
     <kbd>sin(pi)</kbd>
     0.0000000000
     <kbd>alpha = beta1 = 2.3</kbd>
     2.3000000000
     <kbd>alpha</kbd>
     2.3000000000
     <kbd>ln(alpha)</kbd>
     0.8329091229
     <kbd>exp(ln(beta1))</kbd>
     2.3000000000
     $
</pre>
   <p>Note that multiple assignment and nested function calls are permitted.

<ul class="menu">
<li><a accesskey="1" href="#Mfcalc-Decl">Decl</a>:       Bison declarations for multi-function calculator. 
<li><a accesskey="2" href="#Mfcalc-Rules">Rules</a>:     Grammar rules for the calculator. 
<li><a accesskey="3" href="#Mfcalc-Symtab">Symtab</a>:   Symbol table management subroutines. 
</ul>

<div class="node">
<p><hr>
<a name="Mfcalc-Decl"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Mfcalc-Rules">Mfcalc Rules</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Multi_002dfunction-Calc">Multi-function Calc</a>

</div>

<h4 class="subsection">2.5.1 Declarations for <code>mfcalc</code></h4>

<p>Here are the C and Bison declarations for the multi-function calculator.

<pre class="smallexample">     %{
       #include &lt;math.h&gt;  /* For math functions, cos(), sin(), etc.  */
       #include "calc.h"  /* Contains definition of `symrec'.  */
       int yylex (void);
       void yyerror (char const *);
     %}
     %union {
       double    val;   /* For returning numbers.  */
       symrec  *tptr;   /* For returning symbol-table pointers.  */
     }
     %token &lt;val&gt;  NUM        /* Simple double precision number.  */
     %token &lt;tptr&gt; VAR FNCT   /* Variable and Function.  */
     %type  &lt;val&gt;  exp
     
     %right '='
     %left '-' '+'
     %left '*' '/'
     %left NEG     /* negation--unary minus */
     %right '^'    /* exponentiation */
     %% /* The grammar follows.  */
</pre>
   <p>The above grammar introduces only two new features of the Bison language. 
These features allow semantic values to have various data types
(see <a href="#Multiple-Types">More Than One Value Type</a>).

   <p>The <code>%union</code> declaration specifies the entire list of possible types;
this is instead of defining <code>YYSTYPE</code>.  The allowable types are now
double-floats (for <code>exp</code> and <code>NUM</code>) and pointers to entries in
the symbol table.  See <a href="#Union-Decl">The Collection of Value Types</a>.

   <p>Since values can now have various types, it is necessary to associate a
type with each grammar symbol whose semantic value is used.  These symbols
are <code>NUM</code>, <code>VAR</code>, <code>FNCT</code>, and <code>exp</code>.  Their
declarations are augmented with information about their data type (placed
between angle brackets).

   <p>The Bison construct <code>%type</code> is used for declaring nonterminal
symbols, just as <code>%token</code> is used for declaring token types.  We
have not used <code>%type</code> before because nonterminal symbols are
normally declared implicitly by the rules that define them.  But
<code>exp</code> must be declared explicitly so we can specify its value type. 
See <a href="#Type-Decl">Nonterminal Symbols</a>.

<div class="node">
<p><hr>
<a name="Mfcalc-Rules"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Mfcalc-Symtab">Mfcalc Symtab</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Mfcalc-Decl">Mfcalc Decl</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Multi_002dfunction-Calc">Multi-function Calc</a>

</div>

<h4 class="subsection">2.5.2 Grammar Rules for <code>mfcalc</code></h4>

<p>Here are the grammar rules for the multi-function calculator. 
Most of them are copied directly from <code>calc</code>; three rules,
those which mention <code>VAR</code> or <code>FNCT</code>, are new.

<pre class="smallexample">     input:   /* empty */
             | input line
     ;
     
     line:
               '\n'
             | exp '\n'   { printf ("\t%.10g\n", $1); }
             | error '\n' { yyerrok;                  }
     ;
     
     exp:      NUM                { $$ = $1;                         }
             | VAR                { $$ = $1-&gt;value.var;              }
             | VAR '=' exp        { $$ = $3; $1-&gt;value.var = $3;     }
             | FNCT '(' exp ')'   { $$ = (*($1-&gt;value.fnctptr))($3); }
             | exp '+' exp        { $$ = $1 + $3;                    }
             | exp '-' exp        { $$ = $1 - $3;                    }
             | exp '*' exp        { $$ = $1 * $3;                    }
             | exp '/' exp        { $$ = $1 / $3;                    }
             | '-' exp  %prec NEG { $$ = -$2;                        }
             | exp '^' exp        { $$ = pow ($1, $3);               }
             | '(' exp ')'        { $$ = $2;                         }
     ;
     /* End of grammar.  */
     %%
</pre>
   <div class="node">
<p><hr>
<a name="Mfcalc-Symtab"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Mfcalc-Rules">Mfcalc Rules</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Multi_002dfunction-Calc">Multi-function Calc</a>

</div>

<h4 class="subsection">2.5.3 The <code>mfcalc</code> Symbol Table</h4>

<p><a name="index-symbol-table-example-67"></a>
The multi-function calculator requires a symbol table to keep track of the
names and meanings of variables and functions.  This doesn't affect the
grammar rules (except for the actions) or the Bison declarations, but it
requires some additional C functions for support.

   <p>The symbol table itself consists of a linked list of records.  Its
definition, which is kept in the header <samp><span class="file">calc.h</span></samp>, is as follows.  It
provides for either functions or variables to be placed in the table.

<pre class="smallexample">     /* Function type.  */
     typedef double (*func_t) (double);
     
     /* Data type for links in the chain of symbols.  */
     struct symrec
     {
       char *name;  /* name of symbol */
       int type;    /* type of symbol: either VAR or FNCT */
       union
       {
         double var;      /* value of a VAR */
         func_t fnctptr;  /* value of a FNCT */
       } value;
       struct symrec *next;  /* link field */
     };
     
     typedef struct symrec symrec;
     
     /* The symbol table: a chain of `struct symrec'.  */
     extern symrec *sym_table;
     
     symrec *putsym (char const *, func_t);
     symrec *getsym (char const *);
</pre>
   <p>The new version of <code>main</code> includes a call to <code>init_table</code>, a
function that initializes the symbol table.  Here it is, and
<code>init_table</code> as well:

<pre class="smallexample">     #include &lt;stdio.h&gt;
     
     /* Called by yyparse on error.  */
     void
     yyerror (char const *s)
     {
       printf ("%s\n", s);
     }
     
     struct init
     {
       char const *fname;
       double (*fnct) (double);
     };
     
     struct init const arith_fncts[] =
     {
       "sin",  sin,
       "cos",  cos,
       "atan", atan,
       "ln",   log,
       "exp",  exp,
       "sqrt", sqrt,
       0, 0
     };
     
     /* The symbol table: a chain of `struct symrec'.  */
     symrec *sym_table;
     
     /* Put arithmetic functions in table.  */
     void
     init_table (void)
     {
       int i;
       symrec *ptr;
       for (i = 0; arith_fncts[i].fname != 0; i++)
         {
           ptr = putsym (arith_fncts[i].fname, FNCT);
           ptr-&gt;value.fnctptr = arith_fncts[i].fnct;
         }
     }
     
     int
     main (void)
     {
       init_table ();
       return yyparse ();
     }
</pre>
   <p>By simply editing the initialization list and adding the necessary include
files, you can add additional functions to the calculator.

   <p>Two important functions allow look-up and installation of symbols in the
symbol table.  The function <code>putsym</code> is passed a name and the type
(<code>VAR</code> or <code>FNCT</code>) of the object to be installed.  The object is
linked to the front of the list, and a pointer to the object is returned. 
The function <code>getsym</code> is passed the name of the symbol to look up.  If
found, a pointer to that symbol is returned; otherwise zero is returned.

<pre class="smallexample">     symrec *
     putsym (char const *sym_name, int sym_type)
     {
       symrec *ptr;
       ptr = (symrec *) malloc (sizeof (symrec));
       ptr-&gt;name = (char *) malloc (strlen (sym_name) + 1);
       strcpy (ptr-&gt;name,sym_name);
       ptr-&gt;type = sym_type;
       ptr-&gt;value.var = 0; /* Set value to 0 even if fctn.  */
       ptr-&gt;next = (struct symrec *)sym_table;
       sym_table = ptr;
       return ptr;
     }
     
     symrec *
     getsym (char const *sym_name)
     {
       symrec *ptr;
       for (ptr = sym_table; ptr != (symrec *) 0;
            ptr = (symrec *)ptr-&gt;next)
         if (strcmp (ptr-&gt;name,sym_name) == 0)
           return ptr;
       return 0;
     }
</pre>
   <p>The function <code>yylex</code> must now recognize variables, numeric values, and
the single-character arithmetic operators.  Strings of alphanumeric
characters with a leading non-digit are recognized as either variables or
functions depending on what the symbol table says about them.

   <p>The string is passed to <code>getsym</code> for look up in the symbol table.  If
the name appears in the table, a pointer to its location and its type
(<code>VAR</code> or <code>FNCT</code>) is returned to <code>yyparse</code>.  If it is not
already in the table, then it is installed as a <code>VAR</code> using
<code>putsym</code>.  Again, a pointer and its type (which must be <code>VAR</code>) is
returned to <code>yyparse</code>.

   <p>No change is needed in the handling of numeric values and arithmetic
operators in <code>yylex</code>.

<pre class="smallexample">     #include &lt;ctype.h&gt;
     
     int
     yylex (void)
     {
       int c;
     
       /* Ignore white space, get first nonwhite character.  */
       while ((c = getchar ()) == ' ' || c == '\t');
     
       if (c == EOF)
         return 0;
     
       /* Char starts a number =&gt; parse the number.         */
       if (c == '.' || isdigit (c))
         {
           ungetc (c, stdin);
           scanf ("%lf", &amp;yylval.val);
           return NUM;
         }
     
       /* Char starts an identifier =&gt; read the name.       */
       if (isalpha (c))
         {
           symrec *s;
           static char *symbuf = 0;
           static int length = 0;
           int i;
     
           /* Initially make the buffer long enough
              for a 40-character symbol name.  */
           if (length == 0)
             length = 40, symbuf = (char *)malloc (length + 1);
     
           i = 0;
           do
             {
               /* If buffer is full, make it bigger.        */
               if (i == length)
                 {
                   length *= 2;
                   symbuf = (char *) realloc (symbuf, length + 1);
                 }
               /* Add this character to the buffer.         */
               symbuf[i++] = c;
               /* Get another character.                    */
               c = getchar ();
             }
           while (isalnum (c));
     
           ungetc (c, stdin);
           symbuf[i] = '\0';
     
           s = getsym (symbuf);
           if (s == 0)
             s = putsym (symbuf, VAR);
           yylval.tptr = s;
           return s-&gt;type;
         }
     
       /* Any other character is a token by itself.        */
       return c;
     }
</pre>
   <p>This program is both powerful and flexible.  You may easily add new
functions, and it is a simple job to modify this code to install
predefined variables such as <code>pi</code> or <code>e</code> as well.

<div class="node">
<p><hr>
<a name="Exercises"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Multi_002dfunction-Calc">Multi-function Calc</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Examples">Examples</a>

</div>

<h3 class="section">2.6 Exercises</h3>

<p><a name="index-exercises-68"></a>
     <ol type=1 start=1>
<li>Add some new functions from <samp><span class="file">math.h</span></samp> to the initialization list.

     <li>Add another array that contains constants and their values.  Then
modify <code>init_table</code> to add these constants to the symbol table. 
It will be easiest to give the constants type <code>VAR</code>.

     <li>Make the program report an error if the user refers to an
uninitialized variable in any way except to store a value in it.
        </ol>

<div class="node">
<p><hr>
<a name="Grammar-File"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Interface">Interface</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Examples">Examples</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="chapter">3 Bison Grammar Files</h2>

<p>Bison takes as input a context-free grammar specification and produces a
C-language function that recognizes correct instances of the grammar.

   <p>The Bison grammar input file conventionally has a name ending in `<samp><span class="samp">.y</span></samp>'. 
See <a href="#Invocation">Invoking Bison</a>.

<ul class="menu">
<li><a accesskey="1" href="#Grammar-Outline">Grammar Outline</a>:    Overall layout of the grammar file. 
<li><a accesskey="2" href="#Symbols">Symbols</a>:            Terminal and nonterminal symbols. 
<li><a accesskey="3" href="#Rules">Rules</a>:              How to write grammar rules. 
<li><a accesskey="4" href="#Recursion">Recursion</a>:          Writing recursive rules. 
<li><a accesskey="5" href="#Semantics">Semantics</a>:          Semantic values and actions. 
<li><a accesskey="6" href="#Locations">Locations</a>:          Locations and actions. 
<li><a accesskey="7" href="#Declarations">Declarations</a>:       All kinds of Bison declarations are described here. 
<li><a accesskey="8" href="#Multiple-Parsers">Multiple Parsers</a>:   Putting more than one Bison parser in one program. 
</ul>

<div class="node">
<p><hr>
<a name="Grammar-Outline"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Symbols">Symbols</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>

</div>

<h3 class="section">3.1 Outline of a Bison Grammar</h3>

<p>A Bison grammar file has four main sections, shown here with the
appropriate delimiters:

<pre class="example">     %{
       <var>Prologue</var>
     %}
     
     <var>Bison declarations</var>
     
     %%
     <var>Grammar rules</var>
     %%
     
     <var>Epilogue</var>
</pre>
   <p>Comments enclosed in `<samp><span class="samp">/* ... */</span></samp>' may appear in any of the sections. 
As a <acronym>GNU</acronym> extension, `<samp><span class="samp">//</span></samp>' introduces a comment that
continues until end of line.

<ul class="menu">
<li><a accesskey="1" href="#Prologue">Prologue</a>:           Syntax and usage of the prologue. 
<li><a accesskey="2" href="#Bison-Declarations">Bison Declarations</a>:   Syntax and usage of the Bison declarations section. 
<li><a accesskey="3" href="#Grammar-Rules">Grammar Rules</a>:      Syntax and usage of the grammar rules section. 
<li><a accesskey="4" href="#Epilogue">Epilogue</a>:           Syntax and usage of the epilogue. 
</ul>

<div class="node">
<p><hr>
<a name="Prologue"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Bison-Declarations">Bison Declarations</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Grammar-Outline">Grammar Outline</a>

</div>

<h4 class="subsection">3.1.1 The prologue</h4>

<p><a name="index-declarations-section-69"></a><a name="index-Prologue-70"></a><a name="index-declarations-71"></a>
The <var>Prologue</var> section contains macro definitions and
declarations of functions and variables that are used in the actions in the
grammar rules.  These are copied to the beginning of the parser file so
that they precede the definition of <code>yyparse</code>.  You can use
`<samp><span class="samp">#include</span></samp>' to get the declarations from a header file.  If you don't
need any C declarations, you may omit the `<samp><span class="samp">%{</span></samp>' and `<samp><span class="samp">%}</span></samp>'
delimiters that bracket this section.

   <p>You may have more than one <var>Prologue</var> section, intermixed with the
<var>Bison declarations</var>.  This allows you to have C and Bison
declarations that refer to each other.  For example, the <code>%union</code>
declaration may use types defined in a header file, and you may wish to
prototype functions that take arguments of type <code>YYSTYPE</code>.  This
can be done with two <var>Prologue</var> blocks, one before and one after the
<code>%union</code> declaration.

<pre class="smallexample">     %{
       #include &lt;stdio.h&gt;
       #include "ptypes.h"
     %}
     
     %union {
       long n;
       tree t;  /* <code>tree</code><span class="roman"> is defined in <samp>ptypes.h</samp>.</span> */
     }
     
     %{
       static void print_token_value (FILE *, int, YYSTYPE);
       #define YYPRINT(F, N, L) print_token_value (F, N, L)
     %}
     
     ...
</pre>
   <div class="node">
<p><hr>
<a name="Bison-Declarations"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Grammar-Rules">Grammar Rules</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Prologue">Prologue</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Grammar-Outline">Grammar Outline</a>

</div>

<h4 class="subsection">3.1.2 The Bison Declarations Section</h4>

<p><a name="index-Bison-declarations-_0028introduction_0029-72"></a><a name="index-declarations_002c-Bison-_0028introduction_0029-73"></a>
The <var>Bison declarations</var> section contains declarations that define
terminal and nonterminal symbols, specify precedence, and so on. 
In some simple grammars you may not need any declarations. 
See <a href="#Declarations">Bison Declarations</a>.

<div class="node">
<p><hr>
<a name="Grammar-Rules"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Epilogue">Epilogue</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Bison-Declarations">Bison Declarations</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Grammar-Outline">Grammar Outline</a>

</div>

<h4 class="subsection">3.1.3 The Grammar Rules Section</h4>

<p><a name="index-grammar-rules-section-74"></a><a name="index-rules-section-for-grammar-75"></a>
The <dfn>grammar rules</dfn> section contains one or more Bison grammar
rules, and nothing else.  See <a href="#Rules">Syntax of Grammar Rules</a>.

   <p>There must always be at least one grammar rule, and the first
`<samp><span class="samp">%%</span></samp>' (which precedes the grammar rules) may never be omitted even
if it is the first thing in the file.

<div class="node">
<p><hr>
<a name="Epilogue"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Grammar-Rules">Grammar Rules</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Grammar-Outline">Grammar Outline</a>

</div>

<h4 class="subsection">3.1.4 The epilogue</h4>

<p><a name="index-additional-C-code-section-76"></a><a name="index-epilogue-77"></a><a name="index-C-code_002c-section-for-additional-78"></a>
The <var>Epilogue</var> is copied verbatim to the end of the parser file, just as
the <var>Prologue</var> is copied to the beginning.  This is the most convenient
place to put anything that you want to have in the parser file but which need
not come before the definition of <code>yyparse</code>.  For example, the
definitions of <code>yylex</code> and <code>yyerror</code> often go here.  Because
C requires functions to be declared before being used, you often need
to declare functions like <code>yylex</code> and <code>yyerror</code> in the Prologue,
even if you define them int he Epilogue. 
See <a href="#Interface">Parser C-Language Interface</a>.

   <p>If the last section is empty, you may omit the `<samp><span class="samp">%%</span></samp>' that separates it
from the grammar rules.

   <p>The Bison parser itself contains many macros and identifiers whose
names start with `<samp><span class="samp">yy</span></samp>' or `<samp><span class="samp">YY</span></samp>', so it is a
good idea to avoid using any such names (except those documented in this
manual) in the epilogue of the grammar file.

<div class="node">
<p><hr>
<a name="Symbols"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Rules">Rules</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Grammar-Outline">Grammar Outline</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>

</div>

<h3 class="section">3.2 Symbols, Terminal and Nonterminal</h3>

<p><a name="index-nonterminal-symbol-79"></a><a name="index-terminal-symbol-80"></a><a name="index-token-type-81"></a><a name="index-symbol-82"></a>
<dfn>Symbols</dfn> in Bison grammars represent the grammatical classifications
of the language.

   <p>A <dfn>terminal symbol</dfn> (also known as a <dfn>token type</dfn>) represents a
class of syntactically equivalent tokens.  You use the symbol in grammar
rules to mean that a token in that class is allowed.  The symbol is
represented in the Bison parser by a numeric code, and the <code>yylex</code>
function returns a token type code to indicate what kind of token has been
read.  You don't need to know what the code value is; you can use the
symbol to stand for it.

   <p>A <dfn>nonterminal symbol</dfn> stands for a class of syntactically equivalent
groupings.  The symbol name is used in writing grammar rules.  By convention,
it should be all lower case.

   <p>Symbol names can contain letters, digits (not at the beginning),
underscores and periods.  Periods make sense only in nonterminals.

   <p>There are three ways of writing terminal symbols in the grammar:

     <ul>
<li>A <dfn>named token type</dfn> is written with an identifier, like an
identifier in C.  By convention, it should be all upper case.  Each
such name must be defined with a Bison declaration such as
<code>%token</code>.  See <a href="#Token-Decl">Token Type Names</a>.

     <li><a name="index-character-token-83"></a><a name="index-literal-token-84"></a><a name="index-single_002dcharacter-literal-85"></a>A <dfn>character token type</dfn> (or <dfn>literal character token</dfn>) is
written in the grammar using the same syntax used in C for character
constants; for example, <code>'+'</code> is a character token type.  A
character token type doesn't need to be declared unless you need to
specify its semantic value data type (see <a href="#Value-Type">Data Types of Semantic Values</a>), associativity, or precedence (see <a href="#Precedence">Operator Precedence</a>).

     <p>By convention, a character token type is used only to represent a
token that consists of that particular character.  Thus, the token
type <code>'+'</code> is used to represent the character `<samp><span class="samp">+</span></samp>' as a
token.  Nothing enforces this convention, but if you depart from it,
your program will confuse other readers.

     <p>All the usual escape sequences used in character literals in C can be
used in Bison as well, but you must not use the null character as a
character literal because its numeric code, zero, signifies
end-of-input (see <a href="#Calling-Convention">Calling Convention for <code>yylex</code></a>).  Also, unlike standard C, trigraphs have no
special meaning in Bison character literals, nor is backslash-newline
allowed.

     <li><a name="index-string-token-86"></a><a name="index-literal-string-token-87"></a><a name="index-multicharacter-literal-88"></a>A <dfn>literal string token</dfn> is written like a C string constant; for
example, <code>"&lt;="</code> is a literal string token.  A literal string token
doesn't need to be declared unless you need to specify its semantic
value data type (see <a href="#Value-Type">Value Type</a>), associativity, or precedence
(see <a href="#Precedence">Precedence</a>).

     <p>You can associate the literal string token with a symbolic name as an
alias, using the <code>%token</code> declaration (see <a href="#Token-Decl">Token Declarations</a>).  If you don't do that, the lexical analyzer has to
retrieve the token number for the literal string token from the
<code>yytname</code> table (see <a href="#Calling-Convention">Calling Convention</a>).

     <p><strong>Warning</strong>: literal string tokens do not work in Yacc.

     <p>By convention, a literal string token is used only to represent a token
that consists of that particular string.  Thus, you should use the token
type <code>"&lt;="</code> to represent the string `<samp><span class="samp">&lt;=</span></samp>' as a token.  Bison
does not enforce this convention, but if you depart from it, people who
read your program will be confused.

     <p>All the escape sequences used in string literals in C can be used in
Bison as well.  However, unlike Standard C, trigraphs have no special
meaning in Bison string literals, nor is backslash-newline allowed.  A
literal string token must contain two or more characters; for a token
containing just one character, use a character token (see above). 
</ul>

   <p>How you choose to write a terminal symbol has no effect on its
grammatical meaning.  That depends only on where it appears in rules and
on when the parser function returns that symbol.

   <p>The value returned by <code>yylex</code> is always one of the terminal
symbols, except that a zero or negative value signifies end-of-input. 
Whichever way you write the token type in the grammar rules, you write
it the same way in the definition of <code>yylex</code>.  The numeric code
for a character token type is simply the positive numeric code of the
character, so <code>yylex</code> can use the identical value to generate the
requisite code, though you may need to convert it to <code>unsigned
char</code> to avoid sign-extension on hosts where <code>char</code> is signed. 
Each named token type becomes a C macro in
the parser file, so <code>yylex</code> can use the name to stand for the code. 
(This is why periods don't make sense in terminal symbols.) 
See <a href="#Calling-Convention">Calling Convention for <code>yylex</code></a>.

   <p>If <code>yylex</code> is defined in a separate file, you need to arrange for the
token-type macro definitions to be available there.  Use the `<samp><span class="samp">-d</span></samp>'
option when you run Bison, so that it will write these macro definitions
into a separate header file <samp><var>name</var><span class="file">.tab.h</span></samp> which you can include
in the other source files that need it.  See <a href="#Invocation">Invoking Bison</a>.

   <p>If you want to write a grammar that is portable to any Standard C
host, you must use only non-null character tokens taken from the basic
execution character set of Standard C.  This set consists of the ten
digits, the 52 lower- and upper-case English letters, and the
characters in the following C-language string:

<pre class="example">     "\a\b\t\n\v\f\r !\"#%&amp;'()*+,-./:;&lt;=&gt;?[\\]^_{|}~"
</pre>
   <p>The <code>yylex</code> function and Bison must use a consistent character
set and encoding for character tokens.  For example, if you run Bison in an
<acronym>ASCII</acronym> environment, but then compile and run the resulting program
in an environment that uses an incompatible character set like
<acronym>EBCDIC</acronym>, the resulting program may not work because the
tables generated by Bison will assume <acronym>ASCII</acronym> numeric values for
character tokens.  It is standard
practice for software distributions to contain C source files that
were generated by Bison in an <acronym>ASCII</acronym> environment, so installers on
platforms that are incompatible with <acronym>ASCII</acronym> must rebuild those
files before compiling them.

   <p>The symbol <code>error</code> is a terminal symbol reserved for error recovery
(see <a href="#Error-Recovery">Error Recovery</a>); you shouldn't use it for any other purpose. 
In particular, <code>yylex</code> should never return this value.  The default
value of the error token is 256, unless you explicitly assigned 256 to
one of your tokens with a <code>%token</code> declaration.

<div class="node">
<p><hr>
<a name="Rules"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Recursion">Recursion</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Symbols">Symbols</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>

</div>

<h3 class="section">3.3 Syntax of Grammar Rules</h3>

<p><a name="index-rule-syntax-89"></a><a name="index-grammar-rule-syntax-90"></a><a name="index-syntax-of-grammar-rules-91"></a>
A Bison grammar rule has the following general form:

<pre class="example">     <var>result</var>: <var>components</var>...
             ;
</pre>
   <p class="noindent">where <var>result</var> is the nonterminal symbol that this rule describes,
and <var>components</var> are various terminal and nonterminal symbols that
are put together by this rule (see <a href="#Symbols">Symbols</a>).

   <p>For example,

<pre class="example">     exp:      exp '+' exp
             ;
</pre>
   <p class="noindent">says that two groupings of type <code>exp</code>, with a `<samp><span class="samp">+</span></samp>' token in between,
can be combined into a larger grouping of type <code>exp</code>.

   <p>White space in rules is significant only to separate symbols.  You can add
extra white space as you wish.

   <p>Scattered among the components can be <var>actions</var> that determine
the semantics of the rule.  An action looks like this:

<pre class="example">     {<var>C statements</var>}
</pre>
   <p class="noindent">Usually there is only one action and it follows the components. 
See <a href="#Actions">Actions</a>.

   <p><a name="index-g_t_007c-92"></a>Multiple rules for the same <var>result</var> can be written separately or can
be joined with the vertical-bar character `<samp><span class="samp">|</span></samp>' as follows:

<p class="noindent">They are still considered distinct rules even when joined in this way.

   <p>If <var>components</var> in a rule is empty, it means that <var>result</var> can
match the empty string.  For example, here is how to define a
comma-separated sequence of zero or more <code>exp</code> groupings:

<pre class="example">     expseq:   /* empty */
             | expseq1
             ;
     
     expseq1:  exp
             | expseq1 ',' exp
             ;
</pre>
   <p class="noindent">It is customary to write a comment `<samp><span class="samp">/* empty */</span></samp>' in each rule
with no components.

<div class="node">
<p><hr>
<a name="Recursion"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Semantics">Semantics</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Rules">Rules</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>

</div>

<h3 class="section">3.4 Recursive Rules</h3>

<p><a name="index-recursive-rule-93"></a>
A rule is called <dfn>recursive</dfn> when its <var>result</var> nonterminal appears
also on its right hand side.  Nearly all Bison grammars need to use
recursion, because that is the only way to define a sequence of any number
of a particular thing.  Consider this recursive definition of a
comma-separated sequence of one or more expressions:

<pre class="example">     expseq1:  exp
             | expseq1 ',' exp
             ;
</pre>
   <p><a name="index-left-recursion-94"></a><a name="index-right-recursion-95"></a>Since the recursive use of <code>expseq1</code> is the leftmost symbol in the
right hand side, we call this <dfn>left recursion</dfn>.  By contrast, here
the same construct is defined using <dfn>right recursion</dfn>:

<pre class="example">     expseq1:  exp
             | exp ',' expseq1
             ;
</pre>
   <p class="noindent">Any kind of sequence can be defined using either left recursion or right
recursion, but you should always use left recursion, because it can
parse a sequence of any number of elements with bounded stack space. 
Right recursion uses up space on the Bison stack in proportion to the
number of elements in the sequence, because all the elements must be
shifted onto the stack before the rule can be applied even once. 
See <a href="#Algorithm">The Bison Parser Algorithm</a>, for further explanation
of this.

   <p><a name="index-mutual-recursion-96"></a><dfn>Indirect</dfn> or <dfn>mutual</dfn> recursion occurs when the result of the
rule does not appear directly on its right hand side, but does appear
in rules for other nonterminals which do appear on its right hand
side.

   <p>For example:

<pre class="example">     expr:     primary
             | primary '+' primary
             ;
     
     primary:  constant
             | '(' expr ')'
             ;
</pre>
   <p class="noindent">defines two mutually-recursive nonterminals, since each refers to the
other.

<div class="node">
<p><hr>
<a name="Semantics"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Locations">Locations</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Recursion">Recursion</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>

</div>

<h3 class="section">3.5 Defining Language Semantics</h3>

<p><a name="index-defining-language-semantics-97"></a><a name="index-language-semantics_002c-defining-98"></a>
The grammar rules for a language determine only the syntax.  The semantics
are determined by the semantic values associated with various tokens and
groupings, and by the actions taken when various groupings are recognized.

   <p>For example, the calculator calculates properly because the value
associated with each expression is the proper number; it adds properly
because the action for the grouping `<samp><var>x</var><span class="samp">&nbsp;+&nbsp;</span><var>y</var></samp>'<!-- /@w --> is to add
the numbers associated with <var>x</var> and <var>y</var>.

<ul class="menu">
<li><a accesskey="1" href="#Value-Type">Value Type</a>:         Specifying one data type for all semantic values. 
<li><a accesskey="2" href="#Multiple-Types">Multiple Types</a>:     Specifying several alternative data types. 
<li><a accesskey="3" href="#Actions">Actions</a>:            An action is the semantic definition of a grammar rule. 
<li><a accesskey="4" href="#Action-Types">Action Types</a>:       Specifying data types for actions to operate on. 
<li><a accesskey="5" href="#Mid_002dRule-Actions">Mid-Rule Actions</a>:   Most actions go at the end of a rule. 
                      This says when, why and how to use the exceptional
                        action in the middle of a rule. 
</ul>

<div class="node">
<p><hr>
<a name="Value-Type"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Multiple-Types">Multiple Types</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Semantics">Semantics</a>

</div>

<h4 class="subsection">3.5.1 Data Types of Semantic Values</h4>

<p><a name="index-semantic-value-type-99"></a><a name="index-value-type_002c-semantic-100"></a><a name="index-data-types-of-semantic-values-101"></a><a name="index-default-data-type-102"></a>
In a simple program it may be sufficient to use the same data type for
the semantic values of all language constructs.  This was true in the
<acronym>RPN</acronym> and infix calculator examples (see <a href="#RPN-Calc">Reverse Polish Notation Calculator</a>).

   <p>Bison's default is to use type <code>int</code> for all semantic values.  To
specify some other type, define <code>YYSTYPE</code> as a macro, like this:

<pre class="example">     #define YYSTYPE double
</pre>
   <p class="noindent">This macro definition must go in the prologue of the grammar file
(see <a href="#Grammar-Outline">Outline of a Bison Grammar</a>).

<div class="node">
<p><hr>
<a name="Multiple-Types"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Actions">Actions</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Value-Type">Value Type</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Semantics">Semantics</a>

</div>

<h4 class="subsection">3.5.2 More Than One Value Type</h4>

<p>In most programs, you will need different data types for different kinds
of tokens and groupings.  For example, a numeric constant may need type
<code>int</code> or <code>long</code>, while a string constant needs type <code>char *</code>,
and an identifier might need a pointer to an entry in the symbol table.

   <p>To use more than one data type for semantic values in one parser, Bison
requires you to do two things:

     <ul>
<li>Specify the entire collection of possible data types, with the
<code>%union</code> Bison declaration (see <a href="#Union-Decl">The Collection of Value Types</a>).

     <li>Choose one of those types for each symbol (terminal or nonterminal) for
which semantic values are used.  This is done for tokens with the
<code>%token</code> Bison declaration (see <a href="#Token-Decl">Token Type Names</a>)
and for groupings with the <code>%type</code> Bison declaration (see <a href="#Type-Decl">Nonterminal Symbols</a>). 
</ul>

<div class="node">
<p><hr>
<a name="Actions"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Action-Types">Action Types</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Multiple-Types">Multiple Types</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Semantics">Semantics</a>

</div>

<h4 class="subsection">3.5.3 Actions</h4>

<p><a name="index-action-103"></a><a name="index-g_t_0024_0024-104"></a><a name="index-g_t_0024_0040var_007bn_007d-105"></a>
An action accompanies a syntactic rule and contains C code to be executed
each time an instance of that rule is recognized.  The task of most actions
is to compute a semantic value for the grouping built by the rule from the
semantic values associated with tokens or smaller groupings.

   <p>An action consists of C statements surrounded by braces, much like a
compound statement in C.  An action can contain any sequence of C
statements.  Bison does not look for trigraphs, though, so if your C
code uses trigraphs you should ensure that they do not affect the
nesting of braces or the boundaries of comments, strings, or character
literals.

   <p>An action can be placed at any position in the rule;
it is executed at that position.  Most rules have just one action at the
end of the rule, following all the components.  Actions in the middle of
a rule are tricky and used only for special purposes (see <a href="#Mid_002dRule-Actions">Actions in Mid-Rule</a>).

   <p>The C code in an action can refer to the semantic values of the components
matched by the rule with the construct <code>$</code><var>n</var>, which stands for
the value of the <var>n</var>th component.  The semantic value for the grouping
being constructed is <code>$$</code>.  (Bison translates both of these constructs
into array element references when it copies the actions into the parser
file.)

   <p>Here is a typical example:

<pre class="example">     exp:    ...
             | exp '+' exp
                 { $$ = $1 + $3; }
</pre>
   <p class="noindent">This rule constructs an <code>exp</code> from two smaller <code>exp</code> groupings
connected by a plus-sign token.  In the action, <code>$1</code> and <code>$3</code>
refer to the semantic values of the two component <code>exp</code> groupings,
which are the first and third symbols on the right hand side of the rule. 
The sum is stored into <code>$$</code> so that it becomes the semantic value of
the addition-expression just recognized by the rule.  If there were a
useful semantic value associated with the `<samp><span class="samp">+</span></samp>' token, it could be
referred to as <code>$2</code>.

   <p>Note that the vertical-bar character `<samp><span class="samp">|</span></samp>' is really a rule
separator, and actions are attached to a single rule.  This is a
difference with tools like Flex, for which `<samp><span class="samp">|</span></samp>' stands for either
&ldquo;or&rdquo;, or &ldquo;the same action as that of the next rule&rdquo;.  In the
following example, the action is triggered only when `<samp><span class="samp">b</span></samp>' is found:

<pre class="example">     a-or-b: 'a'|'b'   { a_or_b_found = 1; };
</pre>
   <p><a name="index-default-action-106"></a>If you don't specify an action for a rule, Bison supplies a default:
<code>$$&nbsp;=&nbsp;$1</code>.<!-- /@w -->  Thus, the value of the first symbol in the rule
becomes the value of the whole rule.  Of course, the default action is
valid only if the two data types match.  There is no meaningful default
action for an empty rule; every empty rule must have an explicit action
unless the rule's value does not matter.

   <p><code>$</code><var>n</var> with <var>n</var> zero or negative is allowed for reference
to tokens and groupings on the stack <em>before</em> those that match the
current rule.  This is a very risky practice, and to use it reliably
you must be certain of the context in which the rule is applied.  Here
is a case in which you can use this reliably:

<pre class="example">     foo:      expr bar '+' expr  { ... }
             | expr bar '-' expr  { ... }
             ;
     
     bar:      /* empty */
             { previous_expr = $0; }
             ;
</pre>
   <p>As long as <code>bar</code> is used only in the fashion shown here, <code>$0</code>
always refers to the <code>expr</code> which precedes <code>bar</code> in the
definition of <code>foo</code>.

<div class="node">
<p><hr>
<a name="Action-Types"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Mid_002dRule-Actions">Mid-Rule Actions</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Actions">Actions</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Semantics">Semantics</a>

</div>

<h4 class="subsection">3.5.4 Data Types of Values in Actions</h4>

<p><a name="index-action-data-types-107"></a><a name="index-data-types-in-actions-108"></a>
If you have chosen a single data type for semantic values, the <code>$$</code>
and <code>$</code><var>n</var> constructs always have that data type.

   <p>If you have used <code>%union</code> to specify a variety of data types, then you
must declare a choice among these types for each terminal or nonterminal
symbol that can have a semantic value.  Then each time you use <code>$$</code> or
<code>$</code><var>n</var>, its data type is determined by which symbol it refers to
in the rule.  In this example,

<pre class="example">     exp:    ...
             | exp '+' exp
                 { $$ = $1 + $3; }
</pre>
   <p class="noindent"><code>$1</code> and <code>$3</code> refer to instances of <code>exp</code>, so they all
have the data type declared for the nonterminal symbol <code>exp</code>.  If
<code>$2</code> were used, it would have the data type declared for the
terminal symbol <code>'+'</code>, whatever that might be.

   <p>Alternatively, you can specify the data type when you refer to the value,
by inserting `<samp><span class="samp">&lt;</span><var>type</var><span class="samp">&gt;</span></samp>' after the `<samp><span class="samp">$</span></samp>' at the beginning of the
reference.  For example, if you have defined types as shown here:

<pre class="example">     %union {
       int itype;
       double dtype;
     }
</pre>
   <p class="noindent">then you can write <code>$&lt;itype&gt;1</code> to refer to the first subunit of the
rule as an integer, or <code>$&lt;dtype&gt;1</code> to refer to it as a double.

<div class="node">
<p><hr>
<a name="Mid-Rule-Actions"></a>
<a name="Mid_002dRule-Actions"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Action-Types">Action Types</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Semantics">Semantics</a>

</div>

<h4 class="subsection">3.5.5 Actions in Mid-Rule</h4>

<p><a name="index-actions-in-mid_002drule-109"></a><a name="index-mid_002drule-actions-110"></a>
Occasionally it is useful to put an action in the middle of a rule. 
These actions are written just like usual end-of-rule actions, but they
are executed before the parser even recognizes the following components.

   <p>A mid-rule action may refer to the components preceding it using
<code>$</code><var>n</var>, but it may not refer to subsequent components because
it is run before they are parsed.

   <p>The mid-rule action itself counts as one of the components of the rule. 
This makes a difference when there is another action later in the same rule
(and usually there is another at the end): you have to count the actions
along with the symbols when working out which number <var>n</var> to use in
<code>$</code><var>n</var>.

   <p>The mid-rule action can also have a semantic value.  The action can set
its value with an assignment to <code>$$</code>, and actions later in the rule
can refer to the value using <code>$</code><var>n</var>.  Since there is no symbol
to name the action, there is no way to declare a data type for the value
in advance, so you must use the `<samp><span class="samp">$&lt;...&gt;</span><var>n</var></samp>' construct to
specify a data type each time you refer to this value.

   <p>There is no way to set the value of the entire rule with a mid-rule
action, because assignments to <code>$$</code> do not have that effect.  The
only way to set the value for the entire rule is with an ordinary action
at the end of the rule.

   <p>Here is an example from a hypothetical compiler, handling a <code>let</code>
statement that looks like `<samp><span class="samp">let (</span><var>variable</var><span class="samp">) </span><var>statement</var></samp>' and
serves to create a variable named <var>variable</var> temporarily for the
duration of <var>statement</var>.  To parse this construct, we must put
<var>variable</var> into the symbol table while <var>statement</var> is parsed, then
remove it afterward.  Here is how it is done:

<pre class="example">     stmt:   LET '(' var ')'
                     { $&lt;context&gt;$ = push_context ();
                       declare_variable ($3); }
             stmt    { $$ = $6;
                       pop_context ($&lt;context&gt;5); }
</pre>
   <p class="noindent">As soon as `<samp><span class="samp">let (</span><var>variable</var><span class="samp">)</span></samp>' has been recognized, the first
action is run.  It saves a copy of the current semantic context (the
list of accessible variables) as its semantic value, using alternative
<code>context</code> in the data-type union.  Then it calls
<code>declare_variable</code> to add the new variable to that list.  Once the
first action is finished, the embedded statement <code>stmt</code> can be
parsed.  Note that the mid-rule action is component number 5, so the
`<samp><span class="samp">stmt</span></samp>' is component number 6.

   <p>After the embedded statement is parsed, its semantic value becomes the
value of the entire <code>let</code>-statement.  Then the semantic value from the
earlier action is used to restore the prior list of variables.  This
removes the temporary <code>let</code>-variable from the list so that it won't
appear to exist while the rest of the program is parsed.

   <p>Taking action before a rule is completely recognized often leads to
conflicts since the parser must commit to a parse in order to execute the
action.  For example, the following two rules, without mid-rule actions,
can coexist in a working parser because the parser can shift the open-brace
token and look at what follows before deciding whether there is a
declaration or not:

<pre class="example">     compound: '{' declarations statements '}'
             | '{' statements '}'
             ;
</pre>
   <p class="noindent">But when we add a mid-rule action as follows, the rules become nonfunctional:

<pre class="example">     compound: { prepare_for_local_variables (); }
               '{' declarations statements '}'
             | '{' statements '}'
             ;
</pre>
   <p class="noindent">Now the parser is forced to decide whether to run the mid-rule action
when it has read no farther than the open-brace.  In other words, it
must commit to using one rule or the other, without sufficient
information to do it correctly.  (The open-brace token is what is called
the <dfn>look-ahead</dfn> token at this time, since the parser is still
deciding what to do about it.  See <a href="#Look_002dAhead">Look-Ahead Tokens</a>.)

   <p>You might think that you could correct the problem by putting identical
actions into the two rules, like this:

<pre class="example">     compound: { prepare_for_local_variables (); }
               '{' declarations statements '}'
             | { prepare_for_local_variables (); }
               '{' statements '}'
             ;
</pre>
   <p class="noindent">But this does not help, because Bison does not realize that the two actions
are identical.  (Bison never tries to understand the C code in an action.)

   <p>If the grammar is such that a declaration can be distinguished from a
statement by the first token (which is true in C), then one solution which
does work is to put the action after the open-brace, like this:

<pre class="example">     compound: '{' { prepare_for_local_variables (); }
               declarations statements '}'
             | '{' statements '}'
             ;
</pre>
   <p class="noindent">Now the first token of the following declaration or statement,
which would in any case tell Bison which rule to use, can still do so.

   <p>Another solution is to bury the action inside a nonterminal symbol which
serves as a subroutine:

<pre class="example">     subroutine: /* empty */
               { prepare_for_local_variables (); }
             ;
     
     compound: subroutine
               '{' declarations statements '}'
             | subroutine
               '{' statements '}'
             ;
</pre>
   <p class="noindent">Now Bison can execute the action in the rule for <code>subroutine</code> without
deciding which rule for <code>compound</code> it will eventually use.  Note that
the action is now at the end of its rule.  Any mid-rule action can be
converted to an end-of-rule action in this way, and this is what Bison
actually does to implement mid-rule actions.

<div class="node">
<p><hr>
<a name="Locations"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Declarations">Declarations</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Semantics">Semantics</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>

</div>

<h3 class="section">3.6 Tracking Locations</h3>

<p><a name="index-location-111"></a><a name="index-textual-position-112"></a><a name="index-position_002c-textual-113"></a>
Though grammar rules and semantic actions are enough to write a fully
functional parser, it can be useful to process some additional information,
especially symbol locations.

<!-- (terminal or not) ? -->
<p>The way locations are handled is defined by providing a data type, and
actions to take when rules are matched.

<ul class="menu">
<li><a accesskey="1" href="#Location-Type">Location Type</a>:                Specifying a data type for locations. 
<li><a accesskey="2" href="#Actions-and-Locations">Actions and Locations</a>:        Using locations in actions. 
<li><a accesskey="3" href="#Location-Default-Action">Location Default Action</a>:      Defining a general way to compute locations. 
</ul>

<div class="node">
<p><hr>
<a name="Location-Type"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Actions-and-Locations">Actions and Locations</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Locations">Locations</a>

</div>

<h4 class="subsection">3.6.1 Data Type of Locations</h4>

<p><a name="index-data-type-of-locations-114"></a><a name="index-default-location-type-115"></a>
Defining a data type for locations is much simpler than for semantic values,
since all tokens and groupings always use the same type.

   <p>The type of locations is specified by defining a macro called <code>YYLTYPE</code>. 
When <code>YYLTYPE</code> is not defined, Bison uses a default structure type with
four members:

<pre class="example">     typedef struct YYLTYPE
     {
       int first_line;
       int first_column;
       int last_line;
       int last_column;
     } YYLTYPE;
</pre>
   <div class="node">
<p><hr>
<a name="Actions-and-Locations"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Location-Default-Action">Location Default Action</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Location-Type">Location Type</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Locations">Locations</a>

</div>

<h4 class="subsection">3.6.2 Actions and Locations</h4>

<p><a name="index-location-actions-116"></a><a name="index-actions_002c-location-117"></a><a name="index-g_t_0040_0040_0024-118"></a><a name="index-g_t_0040_0040_0040var_007bn_007d-119"></a>
Actions are not only useful for defining language semantics, but also for
describing the behavior of the output parser with locations.

   <p>The most obvious way for building locations of syntactic groupings is very
similar to the way semantic values are computed.  In a given rule, several
constructs can be used to access the locations of the elements being matched. 
The location of the <var>n</var>th component of the right hand side is
<code>@</code><var>n</var>, while the location of the left hand side grouping is
<code>@$</code>.

   <p>Here is a basic example using the default data type for locations:

<pre class="example">     exp:    ...
             | exp '/' exp
                 {
                   @$.first_column = @1.first_column;
                   @$.first_line = @1.first_line;
                   @$.last_column = @3.last_column;
                   @$.last_line = @3.last_line;
                   if ($3)
                     $$ = $1 / $3;
                   else
                     {
                       $$ = 1;
                       printf("Division by zero, l%d,c%d-l%d,c%d",
                              @3.first_line, @3.first_column,
                              @3.last_line, @3.last_column);
                     }
                 }
</pre>
   <p>As for semantic values, there is a default action for locations that is
run each time a rule is matched.  It sets the beginning of <code>@$</code> to the
beginning of the first symbol, and the end of <code>@$</code> to the end of the
last symbol.

   <p>With this default action, the location tracking can be fully automatic.  The
example above simply rewrites this way:

<pre class="example">     exp:    ...
             | exp '/' exp
                 {
                   if ($3)
                     $$ = $1 / $3;
                   else
                     {
                       $$ = 1;
                       printf("Division by zero, l%d,c%d-l%d,c%d",
                              @3.first_line, @3.first_column,
                              @3.last_line, @3.last_column);
                     }
                 }
</pre>
   <div class="node">
<p><hr>
<a name="Location-Default-Action"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Actions-and-Locations">Actions and Locations</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Locations">Locations</a>

</div>

<h4 class="subsection">3.6.3 Default Action for Locations</h4>

<p><a name="index-YYLLOC_005fDEFAULT-120"></a>
Actually, actions are not the best place to compute locations.  Since
locations are much more general than semantic values, there is room in
the output parser to redefine the default action to take for each
rule.  The <code>YYLLOC_DEFAULT</code> macro is invoked each time a rule is
matched, before the associated action is run.  It is also invoked
while processing a syntax error, to compute the error's location.

   <p>Most of the time, this macro is general enough to suppress location
dedicated code from semantic actions.

   <p>The <code>YYLLOC_DEFAULT</code> macro takes three parameters.  The first one is
the location of the grouping (the result of the computation).  When a
rule is matched, the second parameter is an array holding locations of
all right hand side elements of the rule being matched, and the third
parameter is the size of the rule's right hand side.  When processing
a syntax error, the second parameter is an array holding locations of
the symbols that were discarded during error processing, and the third
parameter is the number of discarded symbols.

   <p>By default, <code>YYLLOC_DEFAULT</code> is defined this way for simple
<acronym>LALR</acronym>(1) parsers:

<pre class="example">     #define YYLLOC_DEFAULT(Current, Rhs, N)          \
       Current.first_line   = Rhs[1].first_line;      \
       Current.first_column = Rhs[1].first_column;    \
       Current.last_line    = Rhs[N].last_line;       \
       Current.last_column  = Rhs[N].last_column;
</pre>
   <p class="noindent">and like this for <acronym>GLR</acronym> parsers:

<pre class="example">     #define YYLLOC_DEFAULT(Current, Rhs, N)          \
       Current.first_line   = YYRHSLOC(Rhs,1).first_line;      \
       Current.first_column = YYRHSLOC(Rhs,1).first_column;    \
       Current.last_line    = YYRHSLOC(Rhs,N).last_line;       \
       Current.last_column  = YYRHSLOC(Rhs,N).last_column;
</pre>
   <p>When defining <code>YYLLOC_DEFAULT</code>, you should consider that:

     <ul>
<li>All arguments are free of side-effects.  However, only the first one (the
result) should be modified by <code>YYLLOC_DEFAULT</code>.

     <li>For consistency with semantic actions, valid indexes for the location
array range from 1 to <var>n</var>. 
</ul>

<div class="node">
<p><hr>
<a name="Declarations"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Multiple-Parsers">Multiple Parsers</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Locations">Locations</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>

</div>

<h3 class="section">3.7 Bison Declarations</h3>

<p><a name="index-declarations_002c-Bison-121"></a><a name="index-Bison-declarations-122"></a>
The <dfn>Bison declarations</dfn> section of a Bison grammar defines the symbols
used in formulating the grammar and the data types of semantic values. 
See <a href="#Symbols">Symbols</a>.

   <p>All token type names (but not single-character literal tokens such as
<code>'+'</code> and <code>'*'</code>) must be declared.  Nonterminal symbols must be
declared if you need to specify which data type to use for the semantic
value (see <a href="#Multiple-Types">More Than One Value Type</a>).

   <p>The first rule in the file also specifies the start symbol, by default. 
If you want some other symbol to be the start symbol, you must declare
it explicitly (see <a href="#Language-and-Grammar">Languages and Context-Free Grammars</a>).

<ul class="menu">
<li><a accesskey="1" href="#Token-Decl">Token Decl</a>:         Declaring terminal symbols. 
<li><a accesskey="2" href="#Precedence-Decl">Precedence Decl</a>:    Declaring terminals with precedence and associativity. 
<li><a accesskey="3" href="#Union-Decl">Union Decl</a>:         Declaring the set of all semantic value types. 
<li><a accesskey="4" href="#Type-Decl">Type Decl</a>:          Declaring the choice of type for a nonterminal symbol. 
<li><a accesskey="5" href="#Destructor-Decl">Destructor Decl</a>:    Declaring how symbols are freed. 
<li><a accesskey="6" href="#Expect-Decl">Expect Decl</a>:        Suppressing warnings about shift/reduce conflicts. 
<li><a accesskey="7" href="#Start-Decl">Start Decl</a>:         Specifying the start symbol. 
<li><a accesskey="8" href="#Pure-Decl">Pure Decl</a>:          Requesting a reentrant parser. 
<li><a accesskey="9" href="#Decl-Summary">Decl Summary</a>:       Table of all Bison declarations. 
</ul>

<div class="node">
<p><hr>
<a name="Token-Decl"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Precedence-Decl">Precedence Decl</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Declarations">Declarations</a>

</div>

<h4 class="subsection">3.7.1 Token Type Names</h4>

<p><a name="index-declaring-token-type-names-123"></a><a name="index-token-type-names_002c-declaring-124"></a><a name="index-declaring-literal-string-tokens-125"></a><a name="index-g_t_0025token-126"></a>
The basic way to declare a token type name (terminal symbol) is as follows:

<pre class="example">     %token <var>name</var>
</pre>
   <p>Bison will convert this into a <code>#define</code> directive in
the parser, so that the function <code>yylex</code> (if it is in this file)
can use the name <var>name</var> to stand for this token type's code.

   <p>Alternatively, you can use <code>%left</code>, <code>%right</code>, or
<code>%nonassoc</code> instead of <code>%token</code>, if you wish to specify
associativity and precedence.  See <a href="#Precedence-Decl">Operator Precedence</a>.

   <p>You can explicitly specify the numeric code for a token type by appending
an integer value in the field immediately following the token name:

<pre class="example">     %token NUM 300
</pre>
   <p class="noindent">It is generally best, however, to let Bison choose the numeric codes for
all token types.  Bison will automatically select codes that don't conflict
with each other or with normal characters.

   <p>In the event that the stack type is a union, you must augment the
<code>%token</code> or other token declaration to include the data type
alternative delimited by angle-brackets (see <a href="#Multiple-Types">More Than One Value Type</a>).

   <p>For example:

<pre class="example">     %union {              /* define stack type */
       double val;
       symrec *tptr;
     }
     %token &lt;val&gt; NUM      /* define token NUM and its type */
</pre>
   <p>You can associate a literal string token with a token type name by
writing the literal string at the end of a <code>%token</code>
declaration which declares the name.  For example:

<pre class="example">     %token arrow "=&gt;"
</pre>
   <p class="noindent">For example, a grammar for the C language might specify these names with
equivalent literal string tokens:

<pre class="example">     %token  &lt;operator&gt;  OR      "||"
     %token  &lt;operator&gt;  LE 134  "&lt;="
     %left  OR  "&lt;="
</pre>
   <p class="noindent">Once you equate the literal string and the token name, you can use them
interchangeably in further declarations or the grammar rules.  The
<code>yylex</code> function can use the token name or the literal string to
obtain the token type code number (see <a href="#Calling-Convention">Calling Convention</a>).

<div class="node">
<p><hr>
<a name="Precedence-Decl"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Union-Decl">Union Decl</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Token-Decl">Token Decl</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Declarations">Declarations</a>

</div>

<h4 class="subsection">3.7.2 Operator Precedence</h4>

<p><a name="index-precedence-declarations-127"></a><a name="index-declaring-operator-precedence-128"></a><a name="index-operator-precedence_002c-declaring-129"></a>
Use the <code>%left</code>, <code>%right</code> or <code>%nonassoc</code> declaration to
declare a token and specify its precedence and associativity, all at
once.  These are called <dfn>precedence declarations</dfn>. 
See <a href="#Precedence">Operator Precedence</a>, for general information on
operator precedence.

   <p>The syntax of a precedence declaration is the same as that of
<code>%token</code>: either

<pre class="example">     %left <var>symbols</var>...
</pre>
   <p class="noindent">or

<pre class="example">     %left &lt;<var>type</var>&gt; <var>symbols</var>...
</pre>
   <p>And indeed any of these declarations serves the purposes of <code>%token</code>. 
But in addition, they specify the associativity and relative precedence for
all the <var>symbols</var>:

     <ul>
<li>The associativity of an operator <var>op</var> determines how repeated uses
of the operator nest: whether `<samp><var>x</var> <var>op</var> <var>y</var> <var>op</var>
<var>z</var></samp>' is parsed by grouping <var>x</var> with <var>y</var> first or by
grouping <var>y</var> with <var>z</var> first.  <code>%left</code> specifies
left-associativity (grouping <var>x</var> with <var>y</var> first) and
<code>%right</code> specifies right-associativity (grouping <var>y</var> with
<var>z</var> first).  <code>%nonassoc</code> specifies no associativity, which
means that `<samp><var>x</var> <var>op</var> <var>y</var> <var>op</var> <var>z</var></samp>' is
considered a syntax error.

     <li>The precedence of an operator determines how it nests with other operators. 
All the tokens declared in a single precedence declaration have equal
precedence and nest together according to their associativity. 
When two tokens declared in different precedence declarations associate,
the one declared later has the higher precedence and is grouped first. 
</ul>

<div class="node">
<p><hr>
<a name="Union-Decl"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Type-Decl">Type Decl</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Precedence-Decl">Precedence Decl</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Declarations">Declarations</a>

</div>

<h4 class="subsection">3.7.3 The Collection of Value Types</h4>

<p><a name="index-declaring-value-types-130"></a><a name="index-value-types_002c-declaring-131"></a><a name="index-g_t_0025union-132"></a>
The <code>%union</code> declaration specifies the entire collection of possible
data types for semantic values.  The keyword <code>%union</code> is followed by a
pair of braces containing the same thing that goes inside a <code>union</code> in
C.

   <p>For example:

<pre class="example">     %union {
       double val;
       symrec *tptr;
     }
</pre>
   <p class="noindent">This says that the two alternative types are <code>double</code> and <code>symrec
*</code>.  They are given names <code>val</code> and <code>tptr</code>; these names are used
in the <code>%token</code> and <code>%type</code> declarations to pick one of the types
for a terminal or nonterminal symbol (see <a href="#Type-Decl">Nonterminal Symbols</a>).

   <p>As an extension to <acronym>POSIX</acronym>, a tag is allowed after the
<code>union</code>.  For example:

<pre class="example">     %union value {
       double val;
       symrec *tptr;
     }
</pre>
   <p>specifies the union tag <code>value</code>, so the corresponding C type is
<code>union value</code>.  If you do not specify a tag, it defaults to
<code>YYSTYPE</code>.

   <p>Note that, unlike making a <code>union</code> declaration in C, you need not write
a semicolon after the closing brace.

<div class="node">
<p><hr>
<a name="Type-Decl"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Destructor-Decl">Destructor Decl</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Union-Decl">Union Decl</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Declarations">Declarations</a>

</div>

<h4 class="subsection">3.7.4 Nonterminal Symbols</h4>

<p><a name="index-declaring-value-types_002c-nonterminals-133"></a><a name="index-value-types_002c-nonterminals_002c-declaring-134"></a><a name="index-g_t_0025type-135"></a>
When you use <code>%union</code> to specify multiple value types, you must
declare the value type of each nonterminal symbol for which values are
used.  This is done with a <code>%type</code> declaration, like this:

<pre class="example">     %type &lt;<var>type</var>&gt; <var>nonterminal</var>...
</pre>
   <p class="noindent">Here <var>nonterminal</var> is the name of a nonterminal symbol, and
<var>type</var> is the name given in the <code>%union</code> to the alternative
that you want (see <a href="#Union-Decl">The Collection of Value Types</a>).  You
can give any number of nonterminal symbols in the same <code>%type</code>
declaration, if they have the same value type.  Use spaces to separate
the symbol names.

   <p>You can also declare the value type of a terminal symbol.  To do this,
use the same <code>&lt;</code><var>type</var><code>&gt;</code> construction in a declaration for the
terminal symbol.  All kinds of token declarations allow
<code>&lt;</code><var>type</var><code>&gt;</code>.

<div class="node">
<p><hr>
<a name="Destructor-Decl"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Expect-Decl">Expect Decl</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Type-Decl">Type Decl</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Declarations">Declarations</a>

</div>

<h4 class="subsection">3.7.5 Freeing Discarded Symbols</h4>

<p><a name="index-freeing-discarded-symbols-136"></a><a name="index-g_t_0025destructor-137"></a>
Some symbols can be discarded by the parser, typically during error
recovery (see <a href="#Error-Recovery">Error Recovery</a>).  Basically, during error recovery,
embarrassing symbols already pushed on the stack, and embarrassing
tokens coming from the rest of the file are thrown away until the parser
falls on its feet.  If these symbols convey heap based information, this
memory is lost.  While this behavior is tolerable for batch parsers,
such as in compilers, it is unacceptable for parsers that can
possibility &ldquo;never end&rdquo; such as shells, or implementations of
communication protocols.

   <p>The <code>%destructor</code> directive allows for the definition of code that
is called when a symbol is thrown away.

<div class="defun">
&mdash; Directive: <b>%destructor</b><var> { code } symbols<a name="index-g_t_0025destructor-138"></a></var><br>
<blockquote><p><a name="index-g_t_0025destructor-139"></a>Declare that the <var>code</var> must be invoked for each of the
<var>symbols</var> that will be discarded by the parser.  The <var>code</var>
should use <code>$$</code> to designate the semantic value associated to the
<var>symbols</var>.  The additional parser parameters are also avaible
(see <a href="#Parser-Function">The Parser Function <code>yyparse</code></a>).

        <p><strong>Warning:</strong> as of Bison 1.875, this feature is still considered as
experimental, as there was not enough user feedback.  In particular,
the syntax might still change. 
</p></blockquote></div>

   <p>For instance:

<pre class="smallexample">     %union
     {
       char *string;
     }
     %token &lt;string&gt; STRING
     %type  &lt;string&gt; string
     %destructor { free ($$); } STRING string
</pre>
   <p class="noindent">guarantees that when a <code>STRING</code> or a <code>string</code> will be discarded,
its associated memory will be freed.

   <p>Note that in the future, Bison might also consider that right hand side
members that are not mentioned in the action can be destroyed.  For
instance, in:

<pre class="smallexample">     comment: "/*" STRING "*/";
</pre>
   <p class="noindent">the parser is entitled to destroy the semantic value of the
<code>string</code>.  Of course, this will not apply to the default action;
compare:

<pre class="smallexample">     typeless: string;  // $$ = $1 does not apply; $1 is destroyed.
     typefull: string;  // $$ = $1 applies, $1 is not destroyed.
</pre>
   <div class="node">
<p><hr>
<a name="Expect-Decl"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Start-Decl">Start Decl</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Destructor-Decl">Destructor Decl</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Declarations">Declarations</a>

</div>

<h4 class="subsection">3.7.6 Suppressing Conflict Warnings</h4>

<p><a name="index-suppressing-conflict-warnings-140"></a><a name="index-preventing-warnings-about-conflicts-141"></a><a name="index-warnings_002c-preventing-142"></a><a name="index-conflicts_002c-suppressing-warnings-of-143"></a><a name="index-g_t_0025expect-144"></a>
Bison normally warns if there are any conflicts in the grammar
(see <a href="#Shift_002fReduce">Shift/Reduce Conflicts</a>), but most real grammars
have harmless shift/reduce conflicts which are resolved in a predictable
way and would be difficult to eliminate.  It is desirable to suppress
the warning about these conflicts unless the number of conflicts
changes.  You can do this with the <code>%expect</code> declaration.

   <p>The declaration looks like this:

<pre class="example">     %expect <var>n</var>
</pre>
   <p>Here <var>n</var> is a decimal integer.  The declaration says there should be
no warning if there are <var>n</var> shift/reduce conflicts and no
reduce/reduce conflicts.  An error, instead of the usual warning, is
given if there are either more or fewer conflicts, or if there are any
reduce/reduce conflicts.

   <p>In general, using <code>%expect</code> involves these steps:

     <ul>
<li>Compile your grammar without <code>%expect</code>.  Use the `<samp><span class="samp">-v</span></samp>' option
to get a verbose list of where the conflicts occur.  Bison will also
print the number of conflicts.

     <li>Check each of the conflicts to make sure that Bison's default
resolution is what you really want.  If not, rewrite the grammar and
go back to the beginning.

     <li>Add an <code>%expect</code> declaration, copying the number <var>n</var> from the
number which Bison printed. 
</ul>

   <p>Now Bison will stop annoying you about the conflicts you have checked, but
it will warn you again if changes in the grammar result in additional
conflicts.

<div class="node">
<p><hr>
<a name="Start-Decl"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Pure-Decl">Pure Decl</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Expect-Decl">Expect Decl</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Declarations">Declarations</a>

</div>

<h4 class="subsection">3.7.7 The Start-Symbol</h4>

<p><a name="index-declaring-the-start-symbol-145"></a><a name="index-start-symbol_002c-declaring-146"></a><a name="index-default-start-symbol-147"></a><a name="index-g_t_0025start-148"></a>
Bison assumes by default that the start symbol for the grammar is the first
nonterminal specified in the grammar specification section.  The programmer
may override this restriction with the <code>%start</code> declaration as follows:

<pre class="example">     %start <var>symbol</var>
</pre>
   <div class="node">
<p><hr>
<a name="Pure-Decl"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Decl-Summary">Decl Summary</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Start-Decl">Start Decl</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Declarations">Declarations</a>

</div>

<h4 class="subsection">3.7.8 A Pure (Reentrant) Parser</h4>

<p><a name="index-reentrant-parser-149"></a><a name="index-pure-parser-150"></a><a name="index-g_t_0025pure_002dparser-151"></a>
A <dfn>reentrant</dfn> program is one which does not alter in the course of
execution; in other words, it consists entirely of <dfn>pure</dfn> (read-only)
code.  Reentrancy is important whenever asynchronous execution is possible;
for example, a non-reentrant program may not be safe to call from a signal
handler.  In systems with multiple threads of control, a non-reentrant
program must be called only within interlocks.

   <p>Normally, Bison generates a parser which is not reentrant.  This is
suitable for most uses, and it permits compatibility with Yacc.  (The
standard Yacc interfaces are inherently nonreentrant, because they use
statically allocated variables for communication with <code>yylex</code>,
including <code>yylval</code> and <code>yylloc</code>.)

   <p>Alternatively, you can generate a pure, reentrant parser.  The Bison
declaration <code>%pure-parser</code> says that you want the parser to be
reentrant.  It looks like this:

<pre class="example">     %pure-parser
</pre>
   <p>The result is that the communication variables <code>yylval</code> and
<code>yylloc</code> become local variables in <code>yyparse</code>, and a different
calling convention is used for the lexical analyzer function
<code>yylex</code>.  See <a href="#Pure-Calling">Calling Conventions for Pure Parsers</a>, for the details of this.  The variable <code>yynerrs</code> also
becomes local in <code>yyparse</code> (see <a href="#Error-Reporting">The Error Reporting Function <code>yyerror</code></a>).  The convention for calling
<code>yyparse</code> itself is unchanged.

   <p>Whether the parser is pure has nothing to do with the grammar rules. 
You can generate either a pure parser or a nonreentrant parser from any
valid grammar.

<div class="node">
<p><hr>
<a name="Decl-Summary"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Pure-Decl">Pure Decl</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Declarations">Declarations</a>

</div>

<h4 class="subsection">3.7.9 Bison Declaration Summary</h4>

<p><a name="index-Bison-declaration-summary-152"></a><a name="index-declaration-summary-153"></a><a name="index-summary_002c-Bison-declaration-154"></a>
Here is a summary of the declarations used to define a grammar:

<div class="defun">
&mdash; Directive: <b>%union</b><var><a name="index-g_t_0025union-155"></a></var><br>
<blockquote><p>Declare the collection of data types that semantic values may have
(see <a href="#Union-Decl">The Collection of Value Types</a>). 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%token</b><var><a name="index-g_t_0025token-156"></a></var><br>
<blockquote><p>Declare a terminal symbol (token type name) with no precedence
or associativity specified (see <a href="#Token-Decl">Token Type Names</a>). 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%right</b><var><a name="index-g_t_0025right-157"></a></var><br>
<blockquote><p>Declare a terminal symbol (token type name) that is right-associative
(see <a href="#Precedence-Decl">Operator Precedence</a>). 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%left</b><var><a name="index-g_t_0025left-158"></a></var><br>
<blockquote><p>Declare a terminal symbol (token type name) that is left-associative
(see <a href="#Precedence-Decl">Operator Precedence</a>). 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%nonassoc</b><var><a name="index-g_t_0025nonassoc-159"></a></var><br>
<blockquote><p>Declare a terminal symbol (token type name) that is nonassociative
(using it in a way that would be associative is a syntax error)
</p></blockquote></div>
   (see <a href="#Precedence-Decl">Operator Precedence</a>).

<div class="defun">
&mdash; Directive: <b>%type</b><var><a name="index-g_t_0025type-160"></a></var><br>
<blockquote><p>Declare the type of semantic values for a nonterminal symbol
(see <a href="#Type-Decl">Nonterminal Symbols</a>). 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%start</b><var><a name="index-g_t_0025start-161"></a></var><br>
<blockquote><p>Specify the grammar's start symbol (see <a href="#Start-Decl">The Start-Symbol</a>). 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%expect</b><var><a name="index-g_t_0025expect-162"></a></var><br>
<blockquote><p>Declare the expected number of shift-reduce conflicts
(see <a href="#Expect-Decl">Suppressing Conflict Warnings</a>). 
</p></blockquote></div>

   <pre class="sp">

</pre>
In order to change the behavior of <samp><span class="command">bison</span></samp>, use the following
directives:

<div class="defun">
&mdash; Directive: <b>%debug</b><var><a name="index-g_t_0025debug-163"></a></var><br>
<blockquote><p>In the parser file, define the macro <code>YYDEBUG</code> to 1 if it is not
already defined, so that the debugging facilities are compiled. 
</p></blockquote></div>
   See <a href="#Tracing">Tracing Your Parser</a>.

<div class="defun">
&mdash; Directive: <b>%defines</b><var><a name="index-g_t_0025defines-164"></a></var><br>
<blockquote><p>Write an extra output file containing macro definitions for the token
type names defined in the grammar and the semantic value type
<code>YYSTYPE</code>, as well as a few <code>extern</code> variable declarations.

        <p>If the parser output file is named <samp><var>name</var><span class="file">.c</span></samp> then this file
is named <samp><var>name</var><span class="file">.h</span></samp>.

        <p>This output file is essential if you wish to put the definition of
<code>yylex</code> in a separate source file, because <code>yylex</code> needs to
be able to refer to token type codes and the variable
<code>yylval</code>.  See <a href="#Token-Values">Semantic Values of Tokens</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%destructor</b><var><a name="index-g_t_0025destructor-165"></a></var><br>
<blockquote><p>Specifying how the parser should reclaim the memory associated to
discarded symbols. See <a href="#Destructor-Decl">Freeing Discarded Symbols</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%file-prefix="</b><var>prefix"<a name="index-g_t_0025file_002dprefix_003d_0022-166"></a></var><br>
<blockquote><p>Specify a prefix to use for all Bison output file names.  The names are
chosen as if the input file were named <samp><var>prefix</var><span class="file">.y</span></samp>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%locations</b><var><a name="index-g_t_0025locations-167"></a></var><br>
<blockquote><p>Generate the code processing the locations (see <a href="#Action-Features">Special Features for Use in Actions</a>).  This mode is enabled as soon as
the grammar uses the special `<samp><span class="samp">@</span><var>n</var></samp>' tokens, but if your
grammar does not use it, using `<samp><span class="samp">%locations</span></samp>' allows for more
accurate syntax error messages. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%name-prefix="</b><var>prefix"<a name="index-g_t_0025name_002dprefix_003d_0022-168"></a></var><br>
<blockquote><p>Rename the external symbols used in the parser so that they start with
<var>prefix</var> instead of `<samp><span class="samp">yy</span></samp>'.  The precise list of symbols renamed
is <code>yyparse</code>, <code>yylex</code>, <code>yyerror</code>, <code>yynerrs</code>,
<code>yylval</code>, <code>yylloc</code>, <code>yychar</code>, <code>yydebug</code>, and
possible <code>yylloc</code>.  For example, if you use
`<samp><span class="samp">%name-prefix="c_"</span></samp>', the names become <code>c_parse</code>, <code>c_lex</code>,
and so on.  See <a href="#Multiple-Parsers">Multiple Parsers in the Same Program</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%no-parser</b><var><a name="index-g_t_0025no_002dparser-169"></a></var><br>
<blockquote><p>Do not include any C code in the parser file; generate tables only.  The
parser file contains just <code>#define</code> directives and static variable
declarations.

        <p>This option also tells Bison to write the C code for the grammar actions
into a file named <samp><var>filename</var><span class="file">.act</span></samp>, in the form of a
brace-surrounded body fit for a <code>switch</code> statement. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%no-lines</b><var><a name="index-g_t_0025no_002dlines-170"></a></var><br>
<blockquote><p>Don't generate any <code>#line</code> preprocessor commands in the parser
file.  Ordinarily Bison writes these commands in the parser file so that
the C compiler and debuggers will associate errors and object code with
your source file (the grammar file).  This directive causes them to
associate errors with the parser file, treating it an independent source
file in its own right. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%output="</b><var>filename"<a name="index-g_t_0025output_003d_0022-171"></a></var><br>
<blockquote><p>Specify the <var>filename</var> for the parser file. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%pure-parser</b><var><a name="index-g_t_0025pure_002dparser-172"></a></var><br>
<blockquote><p>Request a pure (reentrant) parser program (see <a href="#Pure-Decl">A Pure (Reentrant) Parser</a>). 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%token-table</b><var><a name="index-g_t_0025token_002dtable-173"></a></var><br>
<blockquote><p>Generate an array of token names in the parser file.  The name of the
array is <code>yytname</code>; <code>yytname[</code><var>i</var><code>]</code> is the name of the
token whose internal Bison token code number is <var>i</var>.  The first
three elements of <code>yytname</code> correspond to the predefined tokens
<code>"$end"</code>,
<code>"error"</code>, and <code>"$undefined"</code>; after these come the symbols
defined in the grammar file.

        <p>For single-character literal tokens and literal string tokens, the name
in the table includes the single-quote or double-quote characters: for
example, <code>"'+'"</code> is a single-character literal and <code>"\"&lt;=\""</code>
is a literal string token.  All the characters of the literal string
token appear verbatim in the string found in the table; even
double-quote characters are not escaped.  For example, if the token
consists of three characters `<samp><span class="samp">*"*</span></samp>', its string in <code>yytname</code>
contains `<samp><span class="samp">"*"*"</span></samp>'.  (In C, that would be written as
<code>"\"*\"*\""</code>).

        <p>When you specify <code>%token-table</code>, Bison also generates macro
definitions for macros <code>YYNTOKENS</code>, <code>YYNNTS</code>, and
<code>YYNRULES</code>, and <code>YYNSTATES</code>:

          <dl>
<dt><code>YYNTOKENS</code><dd>The highest token number, plus one. 
<br><dt><code>YYNNTS</code><dd>The number of nonterminal symbols. 
<br><dt><code>YYNRULES</code><dd>The number of grammar rules,
<br><dt><code>YYNSTATES</code><dd>The number of parser states (see <a href="#Parser-States">Parser States</a>). 
</dl>
        </p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%verbose</b><var><a name="index-g_t_0025verbose-174"></a></var><br>
<blockquote><p>Write an extra output file containing verbose descriptions of the
parser states and what is done for each type of look-ahead token in
that state.  See <a href="#Understanding">Understanding Your Parser</a>, for more
information. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%yacc</b><var><a name="index-g_t_0025yacc-175"></a></var><br>
<blockquote><p>Pretend the option <samp><span class="option">--yacc</span></samp> was given, i.e., imitate Yacc,
including its naming conventions.  See <a href="#Bison-Options">Bison Options</a>, for more. 
</p></blockquote></div>

<div class="node">
<p><hr>
<a name="Multiple-Parsers"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Declarations">Declarations</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Grammar-File">Grammar File</a>

</div>

<h3 class="section">3.8 Multiple Parsers in the Same Program</h3>

<p>Most programs that use Bison parse only one language and therefore contain
only one Bison parser.  But what if you want to parse more than one
language with the same program?  Then you need to avoid a name conflict
between different definitions of <code>yyparse</code>, <code>yylval</code>, and so on.

   <p>The easy way to do this is to use the option `<samp><span class="samp">-p </span><var>prefix</var></samp>'
(see <a href="#Invocation">Invoking Bison</a>).  This renames the interface
functions and variables of the Bison parser to start with <var>prefix</var>
instead of `<samp><span class="samp">yy</span></samp>'.  You can use this to give each parser distinct
names that do not conflict.

   <p>The precise list of symbols renamed is <code>yyparse</code>, <code>yylex</code>,
<code>yyerror</code>, <code>yynerrs</code>, <code>yylval</code>, <code>yylloc</code>,
<code>yychar</code> and <code>yydebug</code>.  For example, if you use `<samp><span class="samp">-p c</span></samp>',
the names become <code>cparse</code>, <code>clex</code>, and so on.

   <p><strong>All the other variables and macros associated with Bison are not
renamed.</strong> These others are not global; there is no conflict if the same
name is used in different parsers.  For example, <code>YYSTYPE</code> is not
renamed, but defining this in different ways in different parsers causes
no trouble (see <a href="#Value-Type">Data Types of Semantic Values</a>).

   <p>The `<samp><span class="samp">-p</span></samp>' option works by adding macro definitions to the beginning
of the parser source file, defining <code>yyparse</code> as
<var>prefix</var><code>parse</code>, and so on.  This effectively substitutes one
name for the other in the entire parser file.

<div class="node">
<p><hr>
<a name="Interface"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Algorithm">Algorithm</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Grammar-File">Grammar File</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="chapter">4 Parser C-Language Interface</h2>

<p><a name="index-C_002dlanguage-interface-176"></a><a name="index-interface-177"></a>
The Bison parser is actually a C function named <code>yyparse</code>.  Here we
describe the interface conventions of <code>yyparse</code> and the other
functions that it needs to use.

   <p>Keep in mind that the parser uses many C identifiers starting with
`<samp><span class="samp">yy</span></samp>' and `<samp><span class="samp">YY</span></samp>' for internal purposes.  If you use such an
identifier (aside from those in this manual) in an action or in epilogue
in the grammar file, you are likely to run into trouble.

<ul class="menu">
<li><a accesskey="1" href="#Parser-Function">Parser Function</a>:    How to call <code>yyparse</code> and what it returns. 
<li><a accesskey="2" href="#Lexical">Lexical</a>:            You must supply a function <code>yylex</code>
                        which reads tokens. 
<li><a accesskey="3" href="#Error-Reporting">Error Reporting</a>:    You must supply a function <code>yyerror</code>. 
<li><a accesskey="4" href="#Action-Features">Action Features</a>:    Special features for use in actions. 
</ul>

<div class="node">
<p><hr>
<a name="Parser-Function"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Lexical">Lexical</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Interface">Interface</a>

</div>

<h3 class="section">4.1 The Parser Function <code>yyparse</code></h3>

<p><a name="index-yyparse-178"></a>
You call the function <code>yyparse</code> to cause parsing to occur.  This
function reads tokens, executes actions, and ultimately returns when it
encounters end-of-input or an unrecoverable syntax error.  You can also
write an action which directs <code>yyparse</code> to return immediately
without reading further.

<div class="defun">
&mdash; Function: int <b>yyparse</b> (<var>void</var>)<var><a name="index-yyparse-179"></a></var><br>
<blockquote><p>The value returned by <code>yyparse</code> is 0 if parsing was successful (return
is due to end-of-input).

        <p>The value is 1 if parsing failed (return is due to a syntax error). 
</p></blockquote></div>

   <p>In an action, you can cause immediate return from <code>yyparse</code> by using
these macros:

<div class="defun">
&mdash; Macro: <b>YYACCEPT</b><var><a name="index-YYACCEPT-180"></a></var><br>
<blockquote><p><a name="index-YYACCEPT-181"></a>Return immediately with value 0 (to report success). 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYABORT</b><var><a name="index-YYABORT-182"></a></var><br>
<blockquote><p><a name="index-YYABORT-183"></a>Return immediately with value 1 (to report failure). 
</p></blockquote></div>

<!-- For now, do not document %lex-param and %parse-param, since it's -->
<!-- not clear that the current behavior is stable enough.  For example, -->
<!-- we may need to add %error-param. -->
<div class="node">
<p><hr>
<a name="Lexical"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Error-Reporting">Error Reporting</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Parser-Function">Parser Function</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Interface">Interface</a>

</div>

<h3 class="section">4.2 The Lexical Analyzer Function <code>yylex</code></h3>

<p><a name="index-yylex-184"></a><a name="index-lexical-analyzer-185"></a>
The <dfn>lexical analyzer</dfn> function, <code>yylex</code>, recognizes tokens from
the input stream and returns them to the parser.  Bison does not create
this function automatically; you must write it so that <code>yyparse</code> can
call it.  The function is sometimes referred to as a lexical scanner.

   <p>In simple programs, <code>yylex</code> is often defined at the end of the Bison
grammar file.  If <code>yylex</code> is defined in a separate source file, you
need to arrange for the token-type macro definitions to be available there. 
To do this, use the `<samp><span class="samp">-d</span></samp>' option when you run Bison, so that it will
write these macro definitions into a separate header file
<samp><var>name</var><span class="file">.tab.h</span></samp> which you can include in the other source files
that need it.  See <a href="#Invocation">Invoking Bison</a>.

<ul class="menu">
<li><a accesskey="1" href="#Calling-Convention">Calling Convention</a>:   How <code>yyparse</code> calls <code>yylex</code>. 
<li><a accesskey="2" href="#Token-Values">Token Values</a>:       How <code>yylex</code> must return the semantic value
                        of the token it has read. 
<li><a accesskey="3" href="#Token-Positions">Token Positions</a>:    How <code>yylex</code> must return the text position
                        (line number, etc.) of the token, if the
                        actions want that. 
<li><a accesskey="4" href="#Pure-Calling">Pure Calling</a>:       How the calling convention differs
                        in a pure parser (see <a href="#Pure-Decl">A Pure (Reentrant) Parser</a>). 
</ul>

<div class="node">
<p><hr>
<a name="Calling-Convention"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Token-Values">Token Values</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Lexical">Lexical</a>

</div>

<h4 class="subsection">4.2.1 Calling Convention for <code>yylex</code></h4>

<p>The value that <code>yylex</code> returns must be the positive numeric code
for the type of token it has just found; a zero or negative value
signifies end-of-input.

   <p>When a token is referred to in the grammar rules by a name, that name
in the parser file becomes a C macro whose definition is the proper
numeric code for that token type.  So <code>yylex</code> can use the name
to indicate that type.  See <a href="#Symbols">Symbols</a>.

   <p>When a token is referred to in the grammar rules by a character literal,
the numeric code for that character is also the code for the token type. 
So <code>yylex</code> can simply return that character code, possibly converted
to <code>unsigned char</code> to avoid sign-extension.  The null character
must not be used this way, because its code is zero and that
signifies end-of-input.

   <p>Here is an example showing these things:

<pre class="example">     int
     yylex (void)
     {
       ...
       if (c == EOF)    /* Detect end-of-input.  */
         return 0;
       ...
       if (c == '+' || c == '-')
         return c;      /* Assume token type for `+' is '+'.  */
       ...
       return INT;      /* Return the type of the token.  */
       ...
     }
</pre>
   <p class="noindent">This interface has been designed so that the output from the <code>lex</code>
utility can be used without change as the definition of <code>yylex</code>.

   <p>If the grammar uses literal string tokens, there are two ways that
<code>yylex</code> can determine the token type codes for them:

     <ul>
<li>If the grammar defines symbolic token names as aliases for the
literal string tokens, <code>yylex</code> can use these symbolic names like
all others.  In this case, the use of the literal string tokens in
the grammar file has no effect on <code>yylex</code>.

     <li><code>yylex</code> can find the multicharacter token in the <code>yytname</code>
table.  The index of the token in the table is the token type's code. 
The name of a multicharacter token is recorded in <code>yytname</code> with a
double-quote, the token's characters, and another double-quote.  The
token's characters are not escaped in any way; they appear verbatim in
the contents of the string in the table.

     <p>Here's code for looking up a token in <code>yytname</code>, assuming that the
characters of the token are stored in <code>token_buffer</code>.

     <pre class="smallexample">          for (i = 0; i &lt; YYNTOKENS; i++)
            {
              if (yytname[i] != 0
                  &amp;&amp; yytname[i][0] == '"'
                  &amp;&amp; ! strncmp (yytname[i] + 1, token_buffer,
                                strlen (token_buffer))
                  &amp;&amp; yytname[i][strlen (token_buffer) + 1] == '"'
                  &amp;&amp; yytname[i][strlen (token_buffer) + 2] == 0)
                break;
            }
     </pre>
     <p>The <code>yytname</code> table is generated only if you use the
<code>%token-table</code> declaration.  See <a href="#Decl-Summary">Decl Summary</a>. 
</ul>

<div class="node">
<p><hr>
<a name="Token-Values"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Token-Positions">Token Positions</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Calling-Convention">Calling Convention</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Lexical">Lexical</a>

</div>

<h4 class="subsection">4.2.2 Semantic Values of Tokens</h4>

<p><a name="index-yylval-186"></a>In an ordinary (non-reentrant) parser, the semantic value of the token must
be stored into the global variable <code>yylval</code>.  When you are using
just one data type for semantic values, <code>yylval</code> has that type. 
Thus, if the type is <code>int</code> (the default), you might write this in
<code>yylex</code>:

<pre class="example">       ...
       yylval = value;  /* Put value onto Bison stack.  */
       return INT;      /* Return the type of the token.  */
       ...
</pre>
   <p>When you are using multiple data types, <code>yylval</code>'s type is a union
made from the <code>%union</code> declaration (see <a href="#Union-Decl">The Collection of Value Types</a>).  So when you store a token's value, you
must use the proper member of the union.  If the <code>%union</code>
declaration looks like this:

<pre class="example">     %union {
       int intval;
       double val;
       symrec *tptr;
     }
</pre>
   <p class="noindent">then the code in <code>yylex</code> might look like this:

<pre class="example">       ...
       yylval.intval = value; /* Put value onto Bison stack.  */
       return INT;            /* Return the type of the token.  */
       ...
</pre>
   <div class="node">
<p><hr>
<a name="Token-Positions"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Pure-Calling">Pure Calling</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Token-Values">Token Values</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Lexical">Lexical</a>

</div>

<h4 class="subsection">4.2.3 Textual Positions of Tokens</h4>

<p><a name="index-yylloc-187"></a>If you are using the `<samp><span class="samp">@</span><var>n</var></samp>'-feature (see <a href="#Locations">Tracking Locations</a>) in actions to keep track of the
textual locations of tokens and groupings, then you must provide this
information in <code>yylex</code>.  The function <code>yyparse</code> expects to
find the textual location of a token just parsed in the global variable
<code>yylloc</code>.  So <code>yylex</code> must store the proper data in that
variable.

   <p>By default, the value of <code>yylloc</code> is a structure and you need only
initialize the members that are going to be used by the actions.  The
four members are called <code>first_line</code>, <code>first_column</code>,
<code>last_line</code> and <code>last_column</code>.  Note that the use of this
feature makes the parser noticeably slower.

   <p><a name="index-YYLTYPE-188"></a>The data type of <code>yylloc</code> has the name <code>YYLTYPE</code>.

<div class="node">
<p><hr>
<a name="Pure-Calling"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Token-Positions">Token Positions</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Lexical">Lexical</a>

</div>

<h4 class="subsection">4.2.4 Calling Conventions for Pure Parsers</h4>

<p>When you use the Bison declaration <code>%pure-parser</code> to request a
pure, reentrant parser, the global communication variables <code>yylval</code>
and <code>yylloc</code> cannot be used.  (See <a href="#Pure-Decl">A Pure (Reentrant) Parser</a>.)  In such parsers the two global variables are replaced by
pointers passed as arguments to <code>yylex</code>.  You must declare them as
shown here, and pass the information back by storing it through those
pointers.

<pre class="example">     int
     yylex (YYSTYPE *lvalp, YYLTYPE *llocp)
     {
       ...
       *lvalp = value;  /* Put value onto Bison stack.  */
       return INT;      /* Return the type of the token.  */
       ...
     }
</pre>
   <p>If the grammar file does not use the `<samp><span class="samp">@</span></samp>' constructs to refer to
textual positions, then the type <code>YYLTYPE</code> will not be defined.  In
this case, omit the second argument; <code>yylex</code> will be called with
only one argument.

<div class="node">
<p><hr>
<a name="Error-Reporting"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Action-Features">Action Features</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Lexical">Lexical</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Interface">Interface</a>

</div>

<h3 class="section">4.3 The Error Reporting Function <code>yyerror</code></h3>

<p><a name="index-error-reporting-function-189"></a><a name="index-yyerror-190"></a><a name="index-parse-error-191"></a><a name="index-syntax-error-192"></a>
The Bison parser detects a <dfn>syntax error</dfn> or <dfn>parse error</dfn>
whenever it reads a token which cannot satisfy any syntax rule.  An
action in the grammar can also explicitly proclaim an error, using the
macro <code>YYERROR</code> (see <a href="#Action-Features">Special Features for Use in Actions</a>).

   <p>The Bison parser expects to report the error by calling an error
reporting function named <code>yyerror</code>, which you must supply.  It is
called by <code>yyparse</code> whenever a syntax error is found, and it
receives one argument.  For a syntax error, the string is normally
<code>"syntax&nbsp;error"</code><!-- /@w -->.

   <p><a name="index-g_t_0025error_002dverbose-193"></a>If you invoke the directive <code>%error-verbose</code> in the Bison
declarations section (see <a href="#Bison-Declarations">The Bison Declarations Section</a>), then Bison provides a more verbose and specific error message
string instead of just plain <code>"syntax&nbsp;error"</code><!-- /@w -->.

   <p>The parser can detect one other kind of error: stack overflow.  This
happens when the input contains constructions that are very deeply
nested.  It isn't likely you will encounter this, since the Bison
parser extends its stack automatically up to a very large limit.  But
if overflow happens, <code>yyparse</code> calls <code>yyerror</code> in the usual
fashion, except that the argument string is <code>"parser&nbsp;stack&nbsp;overflow"</code><!-- /@w -->.

   <p>The following definition suffices in simple programs:

<pre class="example">     void
     yyerror (char const *s)
     {
       fprintf (stderr, "%s\n", s);
     }
</pre>
   <p>After <code>yyerror</code> returns to <code>yyparse</code>, the latter will attempt
error recovery if you have written suitable error recovery grammar rules
(see <a href="#Error-Recovery">Error Recovery</a>).  If recovery is impossible, <code>yyparse</code> will
immediately return 1.

   <p>Obviously, in location tracking pure parsers, <code>yyerror</code> should have
an access to the current location.  This is indeed the case for the GLR
parsers, but not for the Yacc parser, for historical reasons.  I.e., if
`<samp><span class="samp">%locations %pure-parser</span></samp>' is passed then the prototypes for
<code>yyerror</code> are:

<pre class="example">     void yyerror (char const *msg);                 /* Yacc parsers.  */
     void yyerror (YYLTYPE *locp, char const *msg);  /* GLR parsers.   */
</pre>
   <p class="noindent">The prototypes are only indications of how the code produced by Bison
uses <code>yyerror</code>.  Bison-generated code always ignores the returned
value, so <code>yyerror</code> can return any type, including <code>void</code>. 
Also, <code>yyerror</code> can be a variadic function; that is why the
message is always passed last.

   <p>Traditionally <code>yyerror</code> returns an <code>int</code> that is always
ignored, but this is purely for historical reasons, and <code>void</code> is
preferable since it more accurately describes the return type for
<code>yyerror</code>.

   <p><a name="index-yynerrs-194"></a>The variable <code>yynerrs</code> contains the number of syntax errors
encountered so far.  Normally this variable is global; but if you
request a pure parser (see <a href="#Pure-Decl">A Pure (Reentrant) Parser</a>)
then it is a local variable which only the actions can access.

<div class="node">
<p><hr>
<a name="Action-Features"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Error-Reporting">Error Reporting</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Interface">Interface</a>

</div>

<h3 class="section">4.4 Special Features for Use in Actions</h3>

<p><a name="index-summary_002c-action-features-195"></a><a name="index-action-features-summary-196"></a>
Here is a table of Bison constructs, variables and macros that
are useful in actions.

<div class="defun">
&mdash; Variable: <b>$$</b><var><a name="index-g_t_0024_0024-197"></a></var><br>
<blockquote><p>Acts like a variable that contains the semantic value for the
grouping made by the current rule.  See <a href="#Actions">Actions</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Variable: <b>$</b><var>n<a name="index-g_t_0024-198"></a></var><br>
<blockquote><p>Acts like a variable that contains the semantic value for the
<var>n</var>th component of the current rule.  See <a href="#Actions">Actions</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Variable: <b>$&lt;</b><var>typealt&gt;$<a name="index-g_t_0024_003c-199"></a></var><br>
<blockquote><p>Like <code>$$</code> but specifies alternative <var>typealt</var> in the union
specified by the <code>%union</code> declaration.  See <a href="#Action-Types">Data Types of Values in Actions</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Variable: <b>$&lt;</b><var>typealt&gt;n<a name="index-g_t_0024_003c-200"></a></var><br>
<blockquote><p>Like <code>$</code><var>n</var> but specifies alternative <var>typealt</var> in the
union specified by the <code>%union</code> declaration. 
See <a href="#Action-Types">Data Types of Values in Actions</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYABORT;</b><var><a name="index-YYABORT_003b-201"></a></var><br>
<blockquote><p>Return immediately from <code>yyparse</code>, indicating failure. 
See <a href="#Parser-Function">The Parser Function <code>yyparse</code></a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYACCEPT;</b><var><a name="index-YYACCEPT_003b-202"></a></var><br>
<blockquote><p>Return immediately from <code>yyparse</code>, indicating success. 
See <a href="#Parser-Function">The Parser Function <code>yyparse</code></a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYBACKUP</b> (<var>token, value</var>)<var>;<a name="index-YYBACKUP-203"></a></var><br>
<blockquote><p><a name="index-YYBACKUP-204"></a>Unshift a token.  This macro is allowed only for rules that reduce
a single value, and only when there is no look-ahead token. 
It is also disallowed in <acronym>GLR</acronym> parsers. 
It installs a look-ahead token with token type <var>token</var> and
semantic value <var>value</var>; then it discards the value that was
going to be reduced by this rule.

        <p>If the macro is used when it is not valid, such as when there is
a look-ahead token already, then it reports a syntax error with
a message `<samp><span class="samp">cannot back up</span></samp>' and performs ordinary error
recovery.

        <p>In either case, the rest of the action is not executed. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYEMPTY</b><var><a name="index-YYEMPTY-205"></a></var><br>
<blockquote><p><a name="index-YYEMPTY-206"></a>Value stored in <code>yychar</code> when there is no look-ahead token. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYERROR;</b><var><a name="index-YYERROR_003b-207"></a></var><br>
<blockquote><p><a name="index-YYERROR-208"></a>Cause an immediate syntax error.  This statement initiates error
recovery just as if the parser itself had detected an error; however, it
does not call <code>yyerror</code>, and does not print any message.  If you
want to print an error message, call <code>yyerror</code> explicitly before
the `<samp><span class="samp">YYERROR;</span></samp>' statement.  See <a href="#Error-Recovery">Error Recovery</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYRECOVERING</b><var><a name="index-YYRECOVERING-209"></a></var><br>
<blockquote><p>This macro stands for an expression that has the value 1 when the parser
is recovering from a syntax error, and 0 the rest of the time. 
See <a href="#Error-Recovery">Error Recovery</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Variable: <b>yychar</b><var><a name="index-yychar-210"></a></var><br>
<blockquote><p>Variable containing the current look-ahead token.  (In a pure parser,
this is actually a local variable within <code>yyparse</code>.)  When there is
no look-ahead token, the value <code>YYEMPTY</code> is stored in the variable. 
See <a href="#Look_002dAhead">Look-Ahead Tokens</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>yyclearin;</b><var><a name="index-yyclearin_003b-211"></a></var><br>
<blockquote><p>Discard the current look-ahead token.  This is useful primarily in
error rules.  See <a href="#Error-Recovery">Error Recovery</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>yyerrok;</b><var><a name="index-yyerrok_003b-212"></a></var><br>
<blockquote><p>Resume generating error messages immediately for subsequent syntax
errors.  This is useful primarily in error rules. 
See <a href="#Error-Recovery">Error Recovery</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Value: <b>@$</b><var><a name="index-g_t_0040_0040_0024-213"></a></var><br>
<blockquote><p><a name="index-g_t_0040_0040_0024-214"></a>Acts like a structure variable containing information on the textual position
of the grouping made by the current rule.  See <a href="#Locations">Tracking Locations</a>.

     <!-- Check if those paragraphs are still useful or not. -->
<!-- @example -->
<!-- struct @{ -->
<!-- int first_line, last_line; -->
<!-- int first_column, last_column; -->
<!-- @}; -->
<!-- @end example -->
<!-- Thus, to get the starting line number of the third component, you would -->
<!-- use @samp{@@3.first_line}. -->
<!-- In order for the members of this structure to contain valid information, -->
<!-- you must make @code{yylex} supply this information about each token. -->
<!-- If you need only certain members, then @code{yylex} need only fill in -->
<!-- those members. -->
<!-- The use of this feature makes the parser noticeably slower. -->
</blockquote></div>

<div class="defun">
&mdash; Value: <b>@</b><var>n</var><var><a name="index-g_t_0040_0040_0040var_007bn_007d-215"></a></var><br>
<blockquote><p><a name="index-g_t_0040_0040_0040var_007bn_007d-216"></a>Acts like a structure variable containing information on the textual position
of the <var>n</var>th component of the current rule.  See <a href="#Locations">Tracking Locations</a>. 
</p></blockquote></div>

<div class="node">
<p><hr>
<a name="Algorithm"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Error-Recovery">Error Recovery</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Interface">Interface</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="chapter">5 The Bison Parser Algorithm</h2>

<p><a name="index-Bison-parser-algorithm-217"></a><a name="index-algorithm-of-parser-218"></a><a name="index-shifting-219"></a><a name="index-reduction-220"></a><a name="index-parser-stack-221"></a><a name="index-stack_002c-parser-222"></a>
As Bison reads tokens, it pushes them onto a stack along with their
semantic values.  The stack is called the <dfn>parser stack</dfn>.  Pushing a
token is traditionally called <dfn>shifting</dfn>.

   <p>For example, suppose the infix calculator has read `<samp><span class="samp">1 + 5 *</span></samp>', with a
`<samp><span class="samp">3</span></samp>' to come.  The stack will have four elements, one for each token
that was shifted.

   <p>But the stack does not always have an element for each token read.  When
the last <var>n</var> tokens and groupings shifted match the components of a
grammar rule, they can be combined according to that rule.  This is called
<dfn>reduction</dfn>.  Those tokens and groupings are replaced on the stack by a
single grouping whose symbol is the result (left hand side) of that rule. 
Running the rule's action is part of the process of reduction, because this
is what computes the semantic value of the resulting grouping.

   <p>For example, if the infix calculator's parser stack contains this:

<pre class="example">     1 + 5 * 3
</pre>
   <p class="noindent">and the next input token is a newline character, then the last three
elements can be reduced to 15 via the rule:

<pre class="example">     expr: expr '*' expr;
</pre>
   <p class="noindent">Then the stack contains just these three elements:

<pre class="example">     1 + 15
</pre>
   <p class="noindent">At this point, another reduction can be made, resulting in the single value
16.  Then the newline token can be shifted.

   <p>The parser tries, by shifts and reductions, to reduce the entire input down
to a single grouping whose symbol is the grammar's start-symbol
(see <a href="#Language-and-Grammar">Languages and Context-Free Grammars</a>).

   <p>This kind of parser is known in the literature as a bottom-up parser.

<ul class="menu">
<li><a accesskey="1" href="#Look_002dAhead">Look-Ahead</a>:         Parser looks one token ahead when deciding what to do. 
<li><a accesskey="2" href="#Shift_002fReduce">Shift/Reduce</a>:       Conflicts: when either shifting or reduction is valid. 
<li><a accesskey="3" href="#Precedence">Precedence</a>:         Operator precedence works by resolving conflicts. 
<li><a accesskey="4" href="#Contextual-Precedence">Contextual Precedence</a>:   When an operator's precedence depends on context. 
<li><a accesskey="5" href="#Parser-States">Parser States</a>:      The parser is a finite-state-machine with stack. 
<li><a accesskey="6" href="#Reduce_002fReduce">Reduce/Reduce</a>:      When two rules are applicable in the same situation. 
<li><a accesskey="7" href="#Mystery-Conflicts">Mystery Conflicts</a>:   Reduce/reduce conflicts that look unjustified. 
<li><a accesskey="8" href="#Generalized-LR-Parsing">Generalized LR Parsing</a>:   Parsing arbitrary context-free grammars. 
<li><a accesskey="9" href="#Stack-Overflow">Stack Overflow</a>:     What happens when stack gets full.  How to avoid it. 
</ul>

<div class="node">
<p><hr>
<a name="Look-Ahead"></a>
<a name="Look_002dAhead"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Shift_002fReduce">Shift/Reduce</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>

</div>

<h3 class="section">5.1 Look-Ahead Tokens</h3>

<p><a name="index-look_002dahead-token-223"></a>
The Bison parser does <em>not</em> always reduce immediately as soon as the
last <var>n</var> tokens and groupings match a rule.  This is because such a
simple strategy is inadequate to handle most languages.  Instead, when a
reduction is possible, the parser sometimes &ldquo;looks ahead&rdquo; at the next
token in order to decide what to do.

   <p>When a token is read, it is not immediately shifted; first it becomes the
<dfn>look-ahead token</dfn>, which is not on the stack.  Now the parser can
perform one or more reductions of tokens and groupings on the stack, while
the look-ahead token remains off to the side.  When no more reductions
should take place, the look-ahead token is shifted onto the stack.  This
does not mean that all possible reductions have been done; depending on the
token type of the look-ahead token, some rules may choose to delay their
application.

   <p>Here is a simple case where look-ahead is needed.  These three rules define
expressions which contain binary addition operators and postfix unary
factorial operators (`<samp><span class="samp">!</span></samp>'), and allow parentheses for grouping.

<pre class="example">     expr:     term '+' expr
             | term
             ;
     
     term:     '(' expr ')'
             | term '!'
             | NUMBER
             ;
</pre>
   <p>Suppose that the tokens `<samp><span class="samp">1&nbsp;+&nbsp;2</span></samp>'<!-- /@w --> have been read and shifted; what
should be done?  If the following token is `<samp><span class="samp">)</span></samp>', then the first three
tokens must be reduced to form an <code>expr</code>.  This is the only valid
course, because shifting the `<samp><span class="samp">)</span></samp>' would produce a sequence of symbols
<code>term&nbsp;')'</code><!-- /@w -->, and no rule allows this.

   <p>If the following token is `<samp><span class="samp">!</span></samp>', then it must be shifted immediately so
that `<samp><span class="samp">2&nbsp;!</span></samp>'<!-- /@w --> can be reduced to make a <code>term</code>.  If instead the
parser were to reduce before shifting, `<samp><span class="samp">1&nbsp;+&nbsp;2</span></samp>'<!-- /@w --> would become an
<code>expr</code>.  It would then be impossible to shift the `<samp><span class="samp">!</span></samp>' because
doing so would produce on the stack the sequence of symbols <code>expr
'!'</code>.  No rule allows that sequence.

   <p><a name="index-yychar-224"></a>The current look-ahead token is stored in the variable <code>yychar</code>. 
See <a href="#Action-Features">Special Features for Use in Actions</a>.

<div class="node">
<p><hr>
<a name="Shift%2fReduce"></a>
<a name="Shift_002fReduce"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Precedence">Precedence</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Look_002dAhead">Look-Ahead</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>

</div>

<h3 class="section">5.2 Shift/Reduce Conflicts</h3>

<p><a name="index-conflicts-225"></a><a name="index-shift_002freduce-conflicts-226"></a><a name="index-dangling-_0040code_007belse_007d-227"></a><a name="index-g_t_0040code_007belse_007d_002c-dangling-228"></a>
Suppose we are parsing a language which has if-then and if-then-else
statements, with a pair of rules like this:

<pre class="example">     if_stmt:
               IF expr THEN stmt
             | IF expr THEN stmt ELSE stmt
             ;
</pre>
   <p class="noindent">Here we assume that <code>IF</code>, <code>THEN</code> and <code>ELSE</code> are
terminal symbols for specific keyword tokens.

   <p>When the <code>ELSE</code> token is read and becomes the look-ahead token, the
contents of the stack (assuming the input is valid) are just right for
reduction by the first rule.  But it is also legitimate to shift the
<code>ELSE</code>, because that would lead to eventual reduction by the second
rule.

   <p>This situation, where either a shift or a reduction would be valid, is
called a <dfn>shift/reduce conflict</dfn>.  Bison is designed to resolve
these conflicts by choosing to shift, unless otherwise directed by
operator precedence declarations.  To see the reason for this, let's
contrast it with the other alternative.

   <p>Since the parser prefers to shift the <code>ELSE</code>, the result is to attach
the else-clause to the innermost if-statement, making these two inputs
equivalent:

<pre class="example">     if x then if y then win (); else lose;
     
     if x then do; if y then win (); else lose; end;
</pre>
   <p>But if the parser chose to reduce when possible rather than shift, the
result would be to attach the else-clause to the outermost if-statement,
making these two inputs equivalent:

<pre class="example">     if x then if y then win (); else lose;
     
     if x then do; if y then win (); end; else lose;
</pre>
   <p>The conflict exists because the grammar as written is ambiguous: either
parsing of the simple nested if-statement is legitimate.  The established
convention is that these ambiguities are resolved by attaching the
else-clause to the innermost if-statement; this is what Bison accomplishes
by choosing to shift rather than reduce.  (It would ideally be cleaner to
write an unambiguous grammar, but that is very hard to do in this case.) 
This particular ambiguity was first encountered in the specifications of
Algol 60 and is called the &ldquo;dangling <code>else</code>&rdquo; ambiguity.

   <p>To avoid warnings from Bison about predictable, legitimate shift/reduce
conflicts, use the <code>%expect </code><var>n</var> declaration.  There will be no
warning as long as the number of shift/reduce conflicts is exactly <var>n</var>. 
See <a href="#Expect-Decl">Suppressing Conflict Warnings</a>.

   <p>The definition of <code>if_stmt</code> above is solely to blame for the
conflict, but the conflict does not actually appear without additional
rules.  Here is a complete Bison input file that actually manifests the
conflict:

<pre class="example">     %token IF THEN ELSE variable
     %%
     stmt:     expr
             | if_stmt
             ;
     
     if_stmt:
               IF expr THEN stmt
             | IF expr THEN stmt ELSE stmt
             ;
     
     expr:     variable
             ;
</pre>
   <div class="node">
<p><hr>
<a name="Precedence"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Contextual-Precedence">Contextual Precedence</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Shift_002fReduce">Shift/Reduce</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>

</div>

<h3 class="section">5.3 Operator Precedence</h3>

<p><a name="index-operator-precedence-229"></a><a name="index-precedence-of-operators-230"></a>
Another situation where shift/reduce conflicts appear is in arithmetic
expressions.  Here shifting is not always the preferred resolution; the
Bison declarations for operator precedence allow you to specify when to
shift and when to reduce.

<ul class="menu">
<li><a accesskey="1" href="#Why-Precedence">Why Precedence</a>:     An example showing why precedence is needed. 
<li><a accesskey="2" href="#Using-Precedence">Using Precedence</a>:   How to specify precedence in Bison grammars. 
<li><a accesskey="3" href="#Precedence-Examples">Precedence Examples</a>:   How these features are used in the previous example. 
<li><a accesskey="4" href="#How-Precedence">How Precedence</a>:     How they work. 
</ul>

<div class="node">
<p><hr>
<a name="Why-Precedence"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Using-Precedence">Using Precedence</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Precedence">Precedence</a>

</div>

<h4 class="subsection">5.3.1 When Precedence is Needed</h4>

<p>Consider the following ambiguous grammar fragment (ambiguous because the
input `<samp><span class="samp">1&nbsp;-&nbsp;2&nbsp;*&nbsp;3</span></samp>'<!-- /@w --> can be parsed in two different ways):

<pre class="example">     expr:     expr '-' expr
             | expr '*' expr
             | expr '&lt;' expr
             | '(' expr ')'
             ...
             ;
</pre>
   <p class="noindent">Suppose the parser has seen the tokens `<samp><span class="samp">1</span></samp>', `<samp><span class="samp">-</span></samp>' and `<samp><span class="samp">2</span></samp>';
should it reduce them via the rule for the subtraction operator?  It
depends on the next token.  Of course, if the next token is `<samp><span class="samp">)</span></samp>', we
must reduce; shifting is invalid because no single rule can reduce the
token sequence `<samp><span class="samp">-&nbsp;2&nbsp;)</span></samp>'<!-- /@w --> or anything starting with that.  But if
the next token is `<samp><span class="samp">*</span></samp>' or `<samp><span class="samp">&lt;</span></samp>', we have a choice: either
shifting or reduction would allow the parse to complete, but with
different results.

   <p>To decide which one Bison should do, we must consider the results.  If
the next operator token <var>op</var> is shifted, then it must be reduced
first in order to permit another opportunity to reduce the difference. 
The result is (in effect) `<samp><span class="samp">1&nbsp;-&nbsp;(2&nbsp;</span><var>op</var><span class="samp">&nbsp;3)</span></samp>'<!-- /@w -->.  On the other
hand, if the subtraction is reduced before shifting <var>op</var>, the result
is `<samp><span class="samp">(1&nbsp;-&nbsp;2)&nbsp;</span><var>op</var><span class="samp">&nbsp;3</span></samp>'<!-- /@w -->.  Clearly, then, the choice of shift or
reduce should depend on the relative precedence of the operators
`<samp><span class="samp">-</span></samp>' and <var>op</var>: `<samp><span class="samp">*</span></samp>' should be shifted first, but not
`<samp><span class="samp">&lt;</span></samp>'.

   <p><a name="index-associativity-231"></a>What about input such as `<samp><span class="samp">1&nbsp;-&nbsp;2&nbsp;-&nbsp;5</span></samp>'<!-- /@w -->; should this be
`<samp><span class="samp">(1&nbsp;-&nbsp;2)&nbsp;-&nbsp;5</span></samp>'<!-- /@w --> or should it be `<samp><span class="samp">1&nbsp;-&nbsp;(2&nbsp;-&nbsp;5)</span></samp>'<!-- /@w -->?  For most
operators we prefer the former, which is called <dfn>left association</dfn>. 
The latter alternative, <dfn>right association</dfn>, is desirable for
assignment operators.  The choice of left or right association is a
matter of whether the parser chooses to shift or reduce when the stack
contains `<samp><span class="samp">1&nbsp;-&nbsp;2</span></samp>'<!-- /@w --> and the look-ahead token is `<samp><span class="samp">-</span></samp>': shifting
makes right-associativity.

<div class="node">
<p><hr>
<a name="Using-Precedence"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Precedence-Examples">Precedence Examples</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Why-Precedence">Why Precedence</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Precedence">Precedence</a>

</div>

<h4 class="subsection">5.3.2 Specifying Operator Precedence</h4>

<p><a name="index-g_t_0025left-232"></a><a name="index-g_t_0025right-233"></a><a name="index-g_t_0025nonassoc-234"></a>
Bison allows you to specify these choices with the operator precedence
declarations <code>%left</code> and <code>%right</code>.  Each such declaration
contains a list of tokens, which are operators whose precedence and
associativity is being declared.  The <code>%left</code> declaration makes all
those operators left-associative and the <code>%right</code> declaration makes
them right-associative.  A third alternative is <code>%nonassoc</code>, which
declares that it is a syntax error to find the same operator twice &ldquo;in a
row&rdquo;.

   <p>The relative precedence of different operators is controlled by the
order in which they are declared.  The first <code>%left</code> or
<code>%right</code> declaration in the file declares the operators whose
precedence is lowest, the next such declaration declares the operators
whose precedence is a little higher, and so on.

<div class="node">
<p><hr>
<a name="Precedence-Examples"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#How-Precedence">How Precedence</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Using-Precedence">Using Precedence</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Precedence">Precedence</a>

</div>

<h4 class="subsection">5.3.3 Precedence Examples</h4>

<p>In our example, we would want the following declarations:

<pre class="example">     %left '&lt;'
     %left '-'
     %left '*'
</pre>
   <p>In a more complete example, which supports other operators as well, we
would declare them in groups of equal precedence.  For example, <code>'+'</code> is
declared with <code>'-'</code>:

<pre class="example">     %left '&lt;' '&gt;' '=' NE LE GE
     %left '+' '-'
     %left '*' '/'
</pre>
   <p class="noindent">(Here <code>NE</code> and so on stand for the operators for &ldquo;not equal&rdquo;
and so on.  We assume that these tokens are more than one character long
and therefore are represented by names, not character literals.)

<div class="node">
<p><hr>
<a name="How-Precedence"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Precedence-Examples">Precedence Examples</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Precedence">Precedence</a>

</div>

<h4 class="subsection">5.3.4 How Precedence Works</h4>

<p>The first effect of the precedence declarations is to assign precedence
levels to the terminal symbols declared.  The second effect is to assign
precedence levels to certain rules: each rule gets its precedence from
the last terminal symbol mentioned in the components.  (You can also
specify explicitly the precedence of a rule.  See <a href="#Contextual-Precedence">Context-Dependent Precedence</a>.)

   <p>Finally, the resolution of conflicts works by comparing the precedence
of the rule being considered with that of the look-ahead token.  If the
token's precedence is higher, the choice is to shift.  If the rule's
precedence is higher, the choice is to reduce.  If they have equal
precedence, the choice is made based on the associativity of that
precedence level.  The verbose output file made by `<samp><span class="samp">-v</span></samp>'
(see <a href="#Invocation">Invoking Bison</a>) says how each conflict was
resolved.

   <p>Not all rules and not all tokens have precedence.  If either the rule or
the look-ahead token has no precedence, then the default is to shift.

<div class="node">
<p><hr>
<a name="Contextual-Precedence"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Parser-States">Parser States</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Precedence">Precedence</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>

</div>

<h3 class="section">5.4 Context-Dependent Precedence</h3>

<p><a name="index-context_002ddependent-precedence-235"></a><a name="index-unary-operator-precedence-236"></a><a name="index-precedence_002c-context_002ddependent-237"></a><a name="index-precedence_002c-unary-operator-238"></a><a name="index-g_t_0025prec-239"></a>
Often the precedence of an operator depends on the context.  This sounds
outlandish at first, but it is really very common.  For example, a minus
sign typically has a very high precedence as a unary operator, and a
somewhat lower precedence (lower than multiplication) as a binary operator.

   <p>The Bison precedence declarations, <code>%left</code>, <code>%right</code> and
<code>%nonassoc</code>, can only be used once for a given token; so a token has
only one precedence declared in this way.  For context-dependent
precedence, you need to use an additional mechanism: the <code>%prec</code>
modifier for rules.

   <p>The <code>%prec</code> modifier declares the precedence of a particular rule by
specifying a terminal symbol whose precedence should be used for that rule. 
It's not necessary for that symbol to appear otherwise in the rule.  The
modifier's syntax is:

<pre class="example">     %prec <var>terminal-symbol</var>
</pre>
   <p class="noindent">and it is written after the components of the rule.  Its effect is to
assign the rule the precedence of <var>terminal-symbol</var>, overriding
the precedence that would be deduced for it in the ordinary way.  The
altered rule precedence then affects how conflicts involving that rule
are resolved (see <a href="#Precedence">Operator Precedence</a>).

   <p>Here is how <code>%prec</code> solves the problem of unary minus.  First, declare
a precedence for a fictitious terminal symbol named <code>UMINUS</code>.  There
are no tokens of this type, but the symbol serves to stand for its
precedence:

<pre class="example">     ...
     %left '+' '-'
     %left '*'
     %left UMINUS
</pre>
   <p>Now the precedence of <code>UMINUS</code> can be used in specific rules:

<pre class="example">     exp:    ...
             | exp '-' exp
             ...
             | '-' exp %prec UMINUS
</pre>
   <div class="node">
<p><hr>
<a name="Parser-States"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Reduce_002fReduce">Reduce/Reduce</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Contextual-Precedence">Contextual Precedence</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>

</div>

<h3 class="section">5.5 Parser States</h3>

<p><a name="index-finite_002dstate-machine-240"></a><a name="index-parser-state-241"></a><a name="index-state-_0028of-parser_0029-242"></a>
The function <code>yyparse</code> is implemented using a finite-state machine. 
The values pushed on the parser stack are not simply token type codes; they
represent the entire sequence of terminal and nonterminal symbols at or
near the top of the stack.  The current state collects all the information
about previous input which is relevant to deciding what to do next.

   <p>Each time a look-ahead token is read, the current parser state together
with the type of look-ahead token are looked up in a table.  This table
entry can say, &ldquo;Shift the look-ahead token.&rdquo;  In this case, it also
specifies the new parser state, which is pushed onto the top of the
parser stack.  Or it can say, &ldquo;Reduce using rule number <var>n</var>.&rdquo;
This means that a certain number of tokens or groupings are taken off
the top of the stack, and replaced by one grouping.  In other words,
that number of states are popped from the stack, and one new state is
pushed.

   <p>There is one other alternative: the table can say that the look-ahead token
is erroneous in the current state.  This causes error processing to begin
(see <a href="#Error-Recovery">Error Recovery</a>).

<div class="node">
<p><hr>
<a name="Reduce%2fReduce"></a>
<a name="Reduce_002fReduce"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Mystery-Conflicts">Mystery Conflicts</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Parser-States">Parser States</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>

</div>

<h3 class="section">5.6 Reduce/Reduce Conflicts</h3>

<p><a name="index-reduce_002freduce-conflict-243"></a><a name="index-conflicts_002c-reduce_002freduce-244"></a>
A reduce/reduce conflict occurs if there are two or more rules that apply
to the same sequence of input.  This usually indicates a serious error
in the grammar.

   <p>For example, here is an erroneous attempt to define a sequence
of zero or more <code>word</code> groupings.

<pre class="example">     sequence: /* empty */
                     { printf ("empty sequence\n"); }
             | maybeword
             | sequence word
                     { printf ("added word %s\n", $2); }
             ;
     
     maybeword: /* empty */
                     { printf ("empty maybeword\n"); }
             | word
                     { printf ("single word %s\n", $1); }
             ;
</pre>
   <p class="noindent">The error is an ambiguity: there is more than one way to parse a single
<code>word</code> into a <code>sequence</code>.  It could be reduced to a
<code>maybeword</code> and then into a <code>sequence</code> via the second rule. 
Alternatively, nothing-at-all could be reduced into a <code>sequence</code>
via the first rule, and this could be combined with the <code>word</code>
using the third rule for <code>sequence</code>.

   <p>There is also more than one way to reduce nothing-at-all into a
<code>sequence</code>.  This can be done directly via the first rule,
or indirectly via <code>maybeword</code> and then the second rule.

   <p>You might think that this is a distinction without a difference, because it
does not change whether any particular input is valid or not.  But it does
affect which actions are run.  One parsing order runs the second rule's
action; the other runs the first rule's action and the third rule's action. 
In this example, the output of the program changes.

   <p>Bison resolves a reduce/reduce conflict by choosing to use the rule that
appears first in the grammar, but it is very risky to rely on this.  Every
reduce/reduce conflict must be studied and usually eliminated.  Here is the
proper way to define <code>sequence</code>:

<pre class="example">     sequence: /* empty */
                     { printf ("empty sequence\n"); }
             | sequence word
                     { printf ("added word %s\n", $2); }
             ;
</pre>
   <p>Here is another common error that yields a reduce/reduce conflict:

<pre class="example">     sequence: /* empty */
             | sequence words
             | sequence redirects
             ;
     
     words:    /* empty */
             | words word
             ;
     
     redirects:/* empty */
             | redirects redirect
             ;
</pre>
   <p class="noindent">The intention here is to define a sequence which can contain either
<code>word</code> or <code>redirect</code> groupings.  The individual definitions of
<code>sequence</code>, <code>words</code> and <code>redirects</code> are error-free, but the
three together make a subtle ambiguity: even an empty input can be parsed
in infinitely many ways!

   <p>Consider: nothing-at-all could be a <code>words</code>.  Or it could be two
<code>words</code> in a row, or three, or any number.  It could equally well be a
<code>redirects</code>, or two, or any number.  Or it could be a <code>words</code>
followed by three <code>redirects</code> and another <code>words</code>.  And so on.

   <p>Here are two ways to correct these rules.  First, to make it a single level
of sequence:

<pre class="example">     sequence: /* empty */
             | sequence word
             | sequence redirect
             ;
</pre>
   <p>Second, to prevent either a <code>words</code> or a <code>redirects</code>
from being empty:

<pre class="example">     sequence: /* empty */
             | sequence words
             | sequence redirects
             ;
     
     words:    word
             | words word
             ;
     
     redirects:redirect
             | redirects redirect
             ;
</pre>
   <div class="node">
<p><hr>
<a name="Mystery-Conflicts"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Generalized-LR-Parsing">Generalized LR Parsing</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Reduce_002fReduce">Reduce/Reduce</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>

</div>

<h3 class="section">5.7 Mysterious Reduce/Reduce Conflicts</h3>

<p>Sometimes reduce/reduce conflicts can occur that don't look warranted. 
Here is an example:

<pre class="example">     %token ID
     
     %%
     def:    param_spec return_spec ','
             ;
     param_spec:
                  type
             |    name_list ':' type
             ;
     return_spec:
                  type
             |    name ':' type
             ;
     type:        ID
             ;
     name:        ID
             ;
     name_list:
                  name
             |    name ',' name_list
             ;
</pre>
   <p>It would seem that this grammar can be parsed with only a single token
of look-ahead: when a <code>param_spec</code> is being read, an <code>ID</code> is
a <code>name</code> if a comma or colon follows, or a <code>type</code> if another
<code>ID</code> follows.  In other words, this grammar is <acronym>LR</acronym>(1).

   <p><a name="index-g_t_0040acronym_007bLR_007d_00281_0029-245"></a><a name="index-g_t_0040acronym_007bLALR_007d_00281_0029-246"></a>However, Bison, like most parser generators, cannot actually handle all
<acronym>LR</acronym>(1) grammars.  In this grammar, two contexts, that after
an <code>ID</code>
at the beginning of a <code>param_spec</code> and likewise at the beginning of
a <code>return_spec</code>, are similar enough that Bison assumes they are the
same.  They appear similar because the same set of rules would be
active&mdash;the rule for reducing to a <code>name</code> and that for reducing to
a <code>type</code>.  Bison is unable to determine at that stage of processing
that the rules would require different look-ahead tokens in the two
contexts, so it makes a single parser state for them both.  Combining
the two contexts causes a conflict later.  In parser terminology, this
occurrence means that the grammar is not <acronym>LALR</acronym>(1).

   <p>In general, it is better to fix deficiencies than to document them.  But
this particular deficiency is intrinsically hard to fix; parser
generators that can handle <acronym>LR</acronym>(1) grammars are hard to write
and tend to
produce parsers that are very large.  In practice, Bison is more useful
as it is now.

   <p>When the problem arises, you can often fix it by identifying the two
parser states that are being confused, and adding something to make them
look distinct.  In the above example, adding one rule to
<code>return_spec</code> as follows makes the problem go away:

<pre class="example">     %token BOGUS
     ...
     %%
     ...
     return_spec:
                  type
             |    name ':' type
             /* This rule is never used.  */
             |    ID BOGUS
             ;
</pre>
   <p>This corrects the problem because it introduces the possibility of an
additional active rule in the context after the <code>ID</code> at the beginning of
<code>return_spec</code>.  This rule is not active in the corresponding context
in a <code>param_spec</code>, so the two contexts receive distinct parser states. 
As long as the token <code>BOGUS</code> is never generated by <code>yylex</code>,
the added rule cannot alter the way actual input is parsed.

   <p>In this particular example, there is another way to solve the problem:
rewrite the rule for <code>return_spec</code> to use <code>ID</code> directly
instead of via <code>name</code>.  This also causes the two confusing
contexts to have different sets of active rules, because the one for
<code>return_spec</code> activates the altered rule for <code>return_spec</code>
rather than the one for <code>name</code>.

<pre class="example">     param_spec:
                  type
             |    name_list ':' type
             ;
     return_spec:
                  type
             |    ID ':' type
             ;
</pre>
   <div class="node">
<p><hr>
<a name="Generalized-LR-Parsing"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Stack-Overflow">Stack Overflow</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Mystery-Conflicts">Mystery Conflicts</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>

</div>

<h3 class="section">5.8 Generalized <acronym>LR</acronym> (<acronym>GLR</acronym>) Parsing</h3>

<p><a name="index-g_t_0040acronym_007bGLR_007d-parsing-247"></a><a name="index-generalized-_0040acronym_007bLR_007d-_0028_0040acronym_007bGLR_007d_0029-parsing-248"></a><a name="index-ambiguous-grammars-249"></a><a name="index-non_002ddeterministic-parsing-250"></a>
Bison produces <em>deterministic</em> parsers that choose uniquely
when to reduce and which reduction to apply
based on a summary of the preceding input and on one extra token of lookahead. 
As a result, normal Bison handles a proper subset of the family of
context-free languages. 
Ambiguous grammars, since they have strings with more than one possible
sequence of reductions cannot have deterministic parsers in this sense. 
The same is true of languages that require more than one symbol of
lookahead, since the parser lacks the information necessary to make a
decision at the point it must be made in a shift-reduce parser. 
Finally, as previously mentioned (see <a href="#Mystery-Conflicts">Mystery Conflicts</a>),
there are languages where Bison's particular choice of how to
summarize the input seen so far loses necessary information.

   <p>When you use the `<samp><span class="samp">%glr-parser</span></samp>' declaration in your grammar file,
Bison generates a parser that uses a different algorithm, called
Generalized <acronym>LR</acronym> (or <acronym>GLR</acronym>).  A Bison <acronym>GLR</acronym>
parser uses the same basic
algorithm for parsing as an ordinary Bison parser, but behaves
differently in cases where there is a shift-reduce conflict that has not
been resolved by precedence rules (see <a href="#Precedence">Precedence</a>) or a
reduce-reduce conflict.  When a <acronym>GLR</acronym> parser encounters such a
situation, it
effectively <em>splits</em> into a several parsers, one for each possible
shift or reduction.  These parsers then proceed as usual, consuming
tokens in lock-step.  Some of the stacks may encounter other conflicts
and split further, with the result that instead of a sequence of states,
a Bison <acronym>GLR</acronym> parsing stack is what is in effect a tree of states.

   <p>In effect, each stack represents a guess as to what the proper parse
is.  Additional input may indicate that a guess was wrong, in which case
the appropriate stack silently disappears.  Otherwise, the semantics
actions generated in each stack are saved, rather than being executed
immediately.  When a stack disappears, its saved semantic actions never
get executed.  When a reduction causes two stacks to become equivalent,
their sets of semantic actions are both saved with the state that
results from the reduction.  We say that two stacks are equivalent
when they both represent the same sequence of states,
and each pair of corresponding states represents a
grammar symbol that produces the same segment of the input token
stream.

   <p>Whenever the parser makes a transition from having multiple
states to having one, it reverts to the normal <acronym>LALR</acronym>(1) parsing
algorithm, after resolving and executing the saved-up actions. 
At this transition, some of the states on the stack will have semantic
values that are sets (actually multisets) of possible actions.  The
parser tries to pick one of the actions by first finding one whose rule
has the highest dynamic precedence, as set by the `<samp><span class="samp">%dprec</span></samp>'
declaration.  Otherwise, if the alternative actions are not ordered by
precedence, but there the same merging function is declared for both
rules by the `<samp><span class="samp">%merge</span></samp>' declaration,
Bison resolves and evaluates both and then calls the merge function on
the result.  Otherwise, it reports an ambiguity.

   <p>It is possible to use a data structure for the <acronym>GLR</acronym> parsing tree that
permits the processing of any <acronym>LALR</acronym>(1) grammar in linear time (in the
size of the input), any unambiguous (not necessarily
<acronym>LALR</acronym>(1)) grammar in
quadratic worst-case time, and any general (possibly ambiguous)
context-free grammar in cubic worst-case time.  However, Bison currently
uses a simpler data structure that requires time proportional to the
length of the input times the maximum number of stacks required for any
prefix of the input.  Thus, really ambiguous or non-deterministic
grammars can require exponential time and space to process.  Such badly
behaving examples, however, are not generally of practical interest. 
Usually, non-determinism in a grammar is local&mdash;the parser is &ldquo;in
doubt&rdquo; only for a few tokens at a time.  Therefore, the current data
structure should generally be adequate.  On <acronym>LALR</acronym>(1) portions of a
grammar, in particular, it is only slightly slower than with the default
Bison parser.

<div class="node">
<p><hr>
<a name="Stack-Overflow"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Generalized-LR-Parsing">Generalized LR Parsing</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Algorithm">Algorithm</a>

</div>

<h3 class="section">5.9 Stack Overflow, and How to Avoid It</h3>

<p><a name="index-stack-overflow-251"></a><a name="index-parser-stack-overflow-252"></a><a name="index-overflow-of-parser-stack-253"></a>
The Bison parser stack can overflow if too many tokens are shifted and
not reduced.  When this happens, the parser function <code>yyparse</code>
returns a nonzero value, pausing only to call <code>yyerror</code> to report
the overflow.

   <p>Because Bison parsers have growing stacks, hitting the upper limit
usually results from using a right recursion instead of a left
recursion, See <a href="#Recursion">Recursive Rules</a>.

   <p><a name="index-YYMAXDEPTH-254"></a>By defining the macro <code>YYMAXDEPTH</code>, you can control how deep the
parser stack can become before a stack overflow occurs.  Define the
macro with a value that is an integer.  This value is the maximum number
of tokens that can be shifted (and not reduced) before overflow. 
It must be a constant expression whose value is known at compile time.

   <p>The stack space allowed is not necessarily allocated.  If you specify a
large value for <code>YYMAXDEPTH</code>, the parser actually allocates a small
stack at first, and then makes it bigger by stages as needed.  This
increasing allocation happens automatically and silently.  Therefore,
you do not need to make <code>YYMAXDEPTH</code> painfully small merely to save
space for ordinary inputs that do not need much stack.

   <p><a name="index-default-stack-limit-255"></a>The default value of <code>YYMAXDEPTH</code>, if you do not define it, is
10000.

   <p><a name="index-YYINITDEPTH-256"></a>You can control how much stack is allocated initially by defining the
macro <code>YYINITDEPTH</code>.  This value too must be a compile-time
constant integer.  The default is 200.

<!-- FIXME: C++ output. -->
<p>Because of semantical differences between C and C++, the
<acronym>LALR</acronym>(1) parsers
in C produced by Bison by compiled as C++ cannot grow.  In this precise
case (compiling a C parser as C++) you are suggested to grow
<code>YYINITDEPTH</code>.  In the near future, a C++ output output will be
provided which addresses this issue.

<div class="node">
<p><hr>
<a name="Error-Recovery"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Context-Dependency">Context Dependency</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Algorithm">Algorithm</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="chapter">6 Error Recovery</h2>

<p><a name="index-error-recovery-257"></a><a name="index-recovery-from-errors-258"></a>
It is not usually acceptable to have a program terminate on a syntax
error.  For example, a compiler should recover sufficiently to parse the
rest of the input file and check it for errors; a calculator should accept
another expression.

   <p>In a simple interactive command parser where each input is one line, it may
be sufficient to allow <code>yyparse</code> to return 1 on error and have the
caller ignore the rest of the input line when that happens (and then call
<code>yyparse</code> again).  But this is inadequate for a compiler, because it
forgets all the syntactic context leading up to the error.  A syntax error
deep within a function in the compiler input should not cause the compiler
to treat the following line like the beginning of a source file.

   <p><a name="index-error-259"></a>You can define how to recover from a syntax error by writing rules to
recognize the special token <code>error</code>.  This is a terminal symbol that
is always defined (you need not declare it) and reserved for error
handling.  The Bison parser generates an <code>error</code> token whenever a
syntax error happens; if you have provided a rule to recognize this token
in the current context, the parse can continue.

   <p>For example:

<pre class="example">     stmnts:  /* empty string */
             | stmnts '\n'
             | stmnts exp '\n'
             | stmnts error '\n'
</pre>
   <p>The fourth rule in this example says that an error followed by a newline
makes a valid addition to any <code>stmnts</code>.

   <p>What happens if a syntax error occurs in the middle of an <code>exp</code>?  The
error recovery rule, interpreted strictly, applies to the precise sequence
of a <code>stmnts</code>, an <code>error</code> and a newline.  If an error occurs in
the middle of an <code>exp</code>, there will probably be some additional tokens
and subexpressions on the stack after the last <code>stmnts</code>, and there
will be tokens to read before the next newline.  So the rule is not
applicable in the ordinary way.

   <p>But Bison can force the situation to fit the rule, by discarding part of
the semantic context and part of the input.  First it discards states
and objects from the stack until it gets back to a state in which the
<code>error</code> token is acceptable.  (This means that the subexpressions
already parsed are discarded, back to the last complete <code>stmnts</code>.) 
At this point the <code>error</code> token can be shifted.  Then, if the old
look-ahead token is not acceptable to be shifted next, the parser reads
tokens and discards them until it finds a token which is acceptable.  In
this example, Bison reads and discards input until the next newline so
that the fourth rule can apply.  Note that discarded symbols are
possible sources of memory leaks, see <a href="#Destructor-Decl">Freeing Discarded Symbols</a>, for a means to reclaim this memory.

   <p>The choice of error rules in the grammar is a choice of strategies for
error recovery.  A simple and useful strategy is simply to skip the rest of
the current input line or current statement if an error is detected:

<pre class="example">     stmnt: error ';'  /* On error, skip until ';' is read.  */
</pre>
   <p>It is also useful to recover to the matching close-delimiter of an
opening-delimiter that has already been parsed.  Otherwise the
close-delimiter will probably appear to be unmatched, and generate another,
spurious error message:

<pre class="example">     primary:  '(' expr ')'
             | '(' error ')'
             ...
             ;
</pre>
   <p>Error recovery strategies are necessarily guesses.  When they guess wrong,
one syntax error often leads to another.  In the above example, the error
recovery rule guesses that an error is due to bad input within one
<code>stmnt</code>.  Suppose that instead a spurious semicolon is inserted in the
middle of a valid <code>stmnt</code>.  After the error recovery rule recovers
from the first error, another syntax error will be found straightaway,
since the text following the spurious semicolon is also an invalid
<code>stmnt</code>.

   <p>To prevent an outpouring of error messages, the parser will output no error
message for another syntax error that happens shortly after the first; only
after three consecutive input tokens have been successfully shifted will
error messages resume.

   <p>Note that rules which accept the <code>error</code> token may have actions, just
as any other rules can.

   <p><a name="index-yyerrok-260"></a>You can make error messages resume immediately by using the macro
<code>yyerrok</code> in an action.  If you do this in the error rule's action, no
error messages will be suppressed.  This macro requires no arguments;
`<samp><span class="samp">yyerrok;</span></samp>' is a valid C statement.

   <p><a name="index-yyclearin-261"></a>The previous look-ahead token is reanalyzed immediately after an error.  If
this is unacceptable, then the macro <code>yyclearin</code> may be used to clear
this token.  Write the statement `<samp><span class="samp">yyclearin;</span></samp>' in the error rule's
action.

   <p>For example, suppose that on a syntax error, an error handling routine is
called that advances the input stream to some point where parsing should
once again commence.  The next symbol returned by the lexical scanner is
probably correct.  The previous look-ahead token ought to be discarded
with `<samp><span class="samp">yyclearin;</span></samp>'.

   <p><a name="index-YYRECOVERING-262"></a>The macro <code>YYRECOVERING</code> stands for an expression that has the
value 1 when the parser is recovering from a syntax error, and 0 the
rest of the time.  A value of 1 indicates that error messages are
currently suppressed for new syntax errors.

<div class="node">
<p><hr>
<a name="Context-Dependency"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Debugging">Debugging</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Error-Recovery">Error Recovery</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="chapter">7 Handling Context Dependencies</h2>

<p>The Bison paradigm is to parse tokens first, then group them into larger
syntactic units.  In many languages, the meaning of a token is affected by
its context.  Although this violates the Bison paradigm, certain techniques
(known as <dfn>kludges</dfn>) may enable you to write Bison parsers for such
languages.

<ul class="menu">
<li><a accesskey="1" href="#Semantic-Tokens">Semantic Tokens</a>:    Token parsing can depend on the semantic context. 
<li><a accesskey="2" href="#Lexical-Tie_002dins">Lexical Tie-ins</a>:    Token parsing can depend on the syntactic context. 
<li><a accesskey="3" href="#Tie_002din-Recovery">Tie-in Recovery</a>:    Lexical tie-ins have implications for how
                        error recovery rules must be written. 
</ul>

   <p>(Actually, &ldquo;kludge&rdquo; means any technique that gets its job done but is
neither clean nor robust.)

<div class="node">
<p><hr>
<a name="Semantic-Tokens"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Lexical-Tie_002dins">Lexical Tie-ins</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Context-Dependency">Context Dependency</a>

</div>

<h3 class="section">7.1 Semantic Info in Token Types</h3>

<p>The C language has a context dependency: the way an identifier is used
depends on what its current meaning is.  For example, consider this:

<pre class="example">     foo (x);
</pre>
   <p>This looks like a function call statement, but if <code>foo</code> is a typedef
name, then this is actually a declaration of <code>x</code>.  How can a Bison
parser for C decide how to parse this input?

   <p>The method used in <acronym>GNU</acronym> C is to have two different token types,
<code>IDENTIFIER</code> and <code>TYPENAME</code>.  When <code>yylex</code> finds an
identifier, it looks up the current declaration of the identifier in order
to decide which token type to return: <code>TYPENAME</code> if the identifier is
declared as a typedef, <code>IDENTIFIER</code> otherwise.

   <p>The grammar rules can then express the context dependency by the choice of
token type to recognize.  <code>IDENTIFIER</code> is accepted as an expression,
but <code>TYPENAME</code> is not.  <code>TYPENAME</code> can start a declaration, but
<code>IDENTIFIER</code> cannot.  In contexts where the meaning of the identifier
is <em>not</em> significant, such as in declarations that can shadow a
typedef name, either <code>TYPENAME</code> or <code>IDENTIFIER</code> is
accepted&mdash;there is one rule for each of the two token types.

   <p>This technique is simple to use if the decision of which kinds of
identifiers to allow is made at a place close to where the identifier is
parsed.  But in C this is not always so: C allows a declaration to
redeclare a typedef name provided an explicit type has been specified
earlier:

<pre class="example">     typedef int foo, bar, lose;
     static foo (bar);        /* <span class="roman">redeclare </span><code>bar</code><span class="roman"> as static variable</span> */
     static int foo (lose);   /* <span class="roman">redeclare </span><code>foo</code><span class="roman"> as function</span> */
</pre>
   <p>Unfortunately, the name being declared is separated from the declaration
construct itself by a complicated syntactic structure&mdash;the &ldquo;declarator&rdquo;.

   <p>As a result, part of the Bison parser for C needs to be duplicated, with
all the nonterminal names changed: once for parsing a declaration in
which a typedef name can be redefined, and once for parsing a
declaration in which that can't be done.  Here is a part of the
duplication, with actions omitted for brevity:

<pre class="example">     initdcl:
               declarator maybeasm '='
               init
             | declarator maybeasm
             ;
     
     notype_initdcl:
               notype_declarator maybeasm '='
               init
             | notype_declarator maybeasm
             ;
</pre>
   <p class="noindent">Here <code>initdcl</code> can redeclare a typedef name, but <code>notype_initdcl</code>
cannot.  The distinction between <code>declarator</code> and
<code>notype_declarator</code> is the same sort of thing.

   <p>There is some similarity between this technique and a lexical tie-in
(described next), in that information which alters the lexical analysis is
changed during parsing by other parts of the program.  The difference is
here the information is global, and is used for other purposes in the
program.  A true lexical tie-in has a special-purpose flag controlled by
the syntactic context.

<div class="node">
<p><hr>
<a name="Lexical-Tie-ins"></a>
<a name="Lexical-Tie_002dins"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Tie_002din-Recovery">Tie-in Recovery</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Semantic-Tokens">Semantic Tokens</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Context-Dependency">Context Dependency</a>

</div>

<h3 class="section">7.2 Lexical Tie-ins</h3>

<p><a name="index-lexical-tie_002din-263"></a>
One way to handle context-dependency is the <dfn>lexical tie-in</dfn>: a flag
which is set by Bison actions, whose purpose is to alter the way tokens are
parsed.

   <p>For example, suppose we have a language vaguely like C, but with a special
construct `<samp><span class="samp">hex (</span><var>hex-expr</var><span class="samp">)</span></samp>'.  After the keyword <code>hex</code> comes
an expression in parentheses in which all integers are hexadecimal.  In
particular, the token `<samp><span class="samp">a1b</span></samp>' must be treated as an integer rather than
as an identifier if it appears in that context.  Here is how you can do it:

<pre class="example">     %{
       int hexflag;
       int yylex (void);
       void yyerror (char const *);
     %}
     %%
     ...
     expr:   IDENTIFIER
             | constant
             | HEX '('
                     { hexflag = 1; }
               expr ')'
                     { hexflag = 0;
                        $$ = $4; }
             | expr '+' expr
                     { $$ = make_sum ($1, $3); }
             ...
             ;
     
     constant:
               INTEGER
             | STRING
             ;
</pre>
   <p class="noindent">Here we assume that <code>yylex</code> looks at the value of <code>hexflag</code>; when
it is nonzero, all integers are parsed in hexadecimal, and tokens starting
with letters are parsed as integers if possible.

   <p>The declaration of <code>hexflag</code> shown in the prologue of the parser file
is needed to make it accessible to the actions (see <a href="#Prologue">The Prologue</a>). 
You must also write the code in <code>yylex</code> to obey the flag.

<div class="node">
<p><hr>
<a name="Tie-in-Recovery"></a>
<a name="Tie_002din-Recovery"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Lexical-Tie_002dins">Lexical Tie-ins</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Context-Dependency">Context Dependency</a>

</div>

<h3 class="section">7.3 Lexical Tie-ins and Error Recovery</h3>

<p>Lexical tie-ins make strict demands on any error recovery rules you have. 
See <a href="#Error-Recovery">Error Recovery</a>.

   <p>The reason for this is that the purpose of an error recovery rule is to
abort the parsing of one construct and resume in some larger construct. 
For example, in C-like languages, a typical error recovery rule is to skip
tokens until the next semicolon, and then start a new statement, like this:

<pre class="example">     stmt:   expr ';'
             | IF '(' expr ')' stmt { ... }
             ...
             error ';'
                     { hexflag = 0; }
             ;
</pre>
   <p>If there is a syntax error in the middle of a `<samp><span class="samp">hex (</span><var>expr</var><span class="samp">)</span></samp>'
construct, this error rule will apply, and then the action for the
completed `<samp><span class="samp">hex (</span><var>expr</var><span class="samp">)</span></samp>' will never run.  So <code>hexflag</code> would
remain set for the entire rest of the input, or until the next <code>hex</code>
keyword, causing identifiers to be misinterpreted as integers.

   <p>To avoid this problem the error recovery rule itself clears <code>hexflag</code>.

   <p>There may also be an error recovery rule that works within expressions. 
For example, there could be a rule which applies within parentheses
and skips to the close-parenthesis:

<pre class="example">     expr:   ...
             | '(' expr ')'
                     { $$ = $2; }
             | '(' error ')'
             ...
</pre>
   <p>If this rule acts within the <code>hex</code> construct, it is not going to abort
that construct (since it applies to an inner level of parentheses within
the construct).  Therefore, it should not clear the flag: the rest of
the <code>hex</code> construct should be parsed with the flag still in effect.

   <p>What if there is an error recovery rule which might abort out of the
<code>hex</code> construct or might not, depending on circumstances?  There is no
way you can write the action to determine whether a <code>hex</code> construct is
being aborted or not.  So if you are using a lexical tie-in, you had better
make sure your error recovery rules are not of this kind.  Each rule must
be such that you can be sure that it always will, or always won't, have to
clear the flag.

<!-- ================================================== Debugging Your Parser -->
<div class="node">
<p><hr>
<a name="Debugging"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Invocation">Invocation</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Context-Dependency">Context Dependency</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="chapter">8 Debugging Your Parser</h2>

<p>Developing a parser can be a challenge, especially if you don't
understand the algorithm (see <a href="#Algorithm">The Bison Parser Algorithm</a>).  Even so, sometimes a detailed description of the automaton
can help (see <a href="#Understanding">Understanding Your Parser</a>), or
tracing the execution of the parser can give some insight on why it
behaves improperly (see <a href="#Tracing">Tracing Your Parser</a>).

<ul class="menu">
<li><a accesskey="1" href="#Understanding">Understanding</a>:      Understanding the structure of your parser. 
<li><a accesskey="2" href="#Tracing">Tracing</a>:            Tracing the execution of your parser. 
</ul>

<div class="node">
<p><hr>
<a name="Understanding"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Tracing">Tracing</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Debugging">Debugging</a>

</div>

<h3 class="section">8.1 Understanding Your Parser</h3>

<p>As documented elsewhere (see <a href="#Algorithm">The Bison Parser Algorithm</a>)
Bison parsers are <dfn>shift/reduce automata</dfn>.  In some cases (much more
frequent than one would hope), looking at this automaton is required to
tune or simply fix a parser.  Bison provides two different
representation of it, either textually or graphically (as a <acronym>VCG</acronym>
file).

   <p>The textual file is generated when the options <samp><span class="option">--report</span></samp> or
<samp><span class="option">--verbose</span></samp> are specified, see See <a href="#Invocation">Invoking Bison</a>.  Its name is made by removing `<samp><span class="samp">.tab.c</span></samp>' or `<samp><span class="samp">.c</span></samp>' from
the parser output file name, and adding `<samp><span class="samp">.output</span></samp>' instead. 
Therefore, if the input file is <samp><span class="file">foo.y</span></samp>, then the parser file is
called <samp><span class="file">foo.tab.c</span></samp> by default.  As a consequence, the verbose
output file is called <samp><span class="file">foo.output</span></samp>.

   <p>The following grammar file, <samp><span class="file">calc.y</span></samp>, will be used in the sequel:

<pre class="example">     %token NUM STR
     %left '+' '-'
     %left '*'
     %%
     exp: exp '+' exp
        | exp '-' exp
        | exp '*' exp
        | exp '/' exp
        | NUM
        ;
     useless: STR;
     %%
</pre>
   <p><samp><span class="command">bison</span></samp> reports:

<pre class="example">     calc.y: warning: 1 useless nonterminal and 1 useless rule
     calc.y:11.1-7: warning: useless nonterminal: useless
     calc.y:11.10-12: warning: useless rule: useless: STR
     calc.y: conflicts: 7 shift/reduce
</pre>
   <p>When given <samp><span class="option">--report=state</span></samp>, in addition to <samp><span class="file">calc.tab.c</span></samp>, it
creates a file <samp><span class="file">calc.output</span></samp> with contents detailed below.  The
order of the output and the exact presentation might vary, but the
interpretation is the same.

   <p>The first section includes details on conflicts that were solved thanks
to precedence and/or associativity:

<pre class="example">     Conflict in state 8 between rule 2 and token '+' resolved as reduce.
     Conflict in state 8 between rule 2 and token '-' resolved as reduce.
     Conflict in state 8 between rule 2 and token '*' resolved as shift.
<br><small class="dots">...</small><br>
</pre>
   <p class="noindent">The next section lists states that still have conflicts.

<pre class="example">     State 8 conflicts: 1 shift/reduce
     State 9 conflicts: 1 shift/reduce
     State 10 conflicts: 1 shift/reduce
     State 11 conflicts: 4 shift/reduce
</pre>
   <p class="noindent"><a name="index-token_002c-useless-264"></a><a name="index-useless-token-265"></a><a name="index-nonterminal_002c-useless-266"></a><a name="index-useless-nonterminal-267"></a><a name="index-rule_002c-useless-268"></a><a name="index-useless-rule-269"></a>The next section reports useless tokens, nonterminal and rules.  Useless
nonterminals and rules are removed in order to produce a smaller parser,
but useless tokens are preserved, since they might be used by the
scanner (note the difference between &ldquo;useless&rdquo; and &ldquo;not used&rdquo;
below):

<pre class="example">     Useless nonterminals:
        useless
     
     Terminals which are not used:
        STR
     
     Useless rules:
     #6     useless: STR;
</pre>
   <p class="noindent">The next section reproduces the exact grammar that Bison used:

<pre class="example">     Grammar
     
       Number, Line, Rule
         0   5 $accept -&gt; exp $end
         1   5 exp -&gt; exp '+' exp
         2   6 exp -&gt; exp '-' exp
         3   7 exp -&gt; exp '*' exp
         4   8 exp -&gt; exp '/' exp
         5   9 exp -&gt; NUM
</pre>
   <p class="noindent">and reports the uses of the symbols:

<pre class="example">     Terminals, with rules where they appear
     
     $end (0) 0
     '*' (42) 3
     '+' (43) 1
     '-' (45) 2
     '/' (47) 4
     error (256)
     NUM (258) 5
     
     Nonterminals, with rules where they appear
     
     $accept (8)
         on left: 0
     exp (9)
         on left: 1 2 3 4 5, on right: 0 1 2 3 4
</pre>
   <p class="noindent"><a name="index-item-270"></a><a name="index-pointed-rule-271"></a><a name="index-rule_002c-pointed-272"></a>Bison then proceeds onto the automaton itself, describing each state
with it set of <dfn>items</dfn>, also known as <dfn>pointed rules</dfn>.  Each
item is a production rule together with a point (marked by `<samp><span class="samp">.</span></samp>')
that the input cursor.

<pre class="example">     state 0
     
         $accept  -&gt;  . exp $   (rule 0)
     
         NUM         shift, and go to state 1
     
         exp         go to state 2
</pre>
   <p>This reads as follows: &ldquo;state 0 corresponds to being at the very
beginning of the parsing, in the initial rule, right before the start
symbol (here, <code>exp</code>).  When the parser returns to this state right
after having reduced a rule that produced an <code>exp</code>, the control
flow jumps to state 2.  If there is no such transition on a nonterminal
symbol, and the lookahead is a <code>NUM</code>, then this token is shifted on
the parse stack, and the control flow jumps to state 1.  Any other
lookahead triggers a syntax error.&rdquo;

   <p><a name="index-core_002c-item-set-273"></a><a name="index-item-set-core-274"></a><a name="index-kernel_002c-item-set-275"></a><a name="index-item-set-core-276"></a>Even though the only active rule in state 0 seems to be rule 0, the
report lists <code>NUM</code> as a lookahead symbol because <code>NUM</code> can be
at the beginning of any rule deriving an <code>exp</code>.  By default Bison
reports the so-called <dfn>core</dfn> or <dfn>kernel</dfn> of the item set, but if
you want to see more detail you can invoke <samp><span class="command">bison</span></samp> with
<samp><span class="option">--report=itemset</span></samp> to list all the items, include those that can
be derived:

<pre class="example">     state 0
     
         $accept  -&gt;  . exp $   (rule 0)
         exp  -&gt;  . exp '+' exp   (rule 1)
         exp  -&gt;  . exp '-' exp   (rule 2)
         exp  -&gt;  . exp '*' exp   (rule 3)
         exp  -&gt;  . exp '/' exp   (rule 4)
         exp  -&gt;  . NUM   (rule 5)
     
         NUM         shift, and go to state 1
     
         exp         go to state 2
</pre>
   <p class="noindent">In the state 1...

<pre class="example">     state 1
     
         exp  -&gt;  NUM .   (rule 5)
     
         $default    reduce using rule 5 (exp)
</pre>
   <p class="noindent">the rule 5, `<samp><span class="samp">exp: NUM;</span></samp>', is completed.  Whatever the lookahead
(`<samp><span class="samp">$default</span></samp>'), the parser will reduce it.  If it was coming from
state 0, then, after this reduction it will return to state 0, and will
jump to state 2 (`<samp><span class="samp">exp: go to state 2</span></samp>').

<pre class="example">     state 2
     
         $accept  -&gt;  exp . $   (rule 0)
         exp  -&gt;  exp . '+' exp   (rule 1)
         exp  -&gt;  exp . '-' exp   (rule 2)
         exp  -&gt;  exp . '*' exp   (rule 3)
         exp  -&gt;  exp . '/' exp   (rule 4)
     
         $           shift, and go to state 3
         '+'         shift, and go to state 4
         '-'         shift, and go to state 5
         '*'         shift, and go to state 6
         '/'         shift, and go to state 7
</pre>
   <p class="noindent">In state 2, the automaton can only shift a symbol.  For instance,
because of the item `<samp><span class="samp">exp -&gt; exp . '+' exp</span></samp>', if the lookahead if
`<samp><span class="samp">+</span></samp>', it will be shifted on the parse stack, and the automaton
control will jump to state 4, corresponding to the item `<samp><span class="samp">exp -&gt; exp
'+' . exp</span></samp>'.  Since there is no default action, any other token than
those listed above will trigger a syntax error.

   <p>The state 3 is named the <dfn>final state</dfn>, or the <dfn>accepting
state</dfn>:

<pre class="example">     state 3
     
         $accept  -&gt;  exp $ .   (rule 0)
     
         $default    accept
</pre>
   <p class="noindent">the initial rule is completed (the start symbol and the end
of input were read), the parsing exits successfully.

   <p>The interpretation of states 4 to 7 is straightforward, and is left to
the reader.

<pre class="example">     state 4
     
         exp  -&gt;  exp '+' . exp   (rule 1)
     
         NUM         shift, and go to state 1
     
         exp         go to state 8
     
     state 5
     
         exp  -&gt;  exp '-' . exp   (rule 2)
     
         NUM         shift, and go to state 1
     
         exp         go to state 9
     
     state 6
     
         exp  -&gt;  exp '*' . exp   (rule 3)
     
         NUM         shift, and go to state 1
     
         exp         go to state 10
     
     state 7
     
         exp  -&gt;  exp '/' . exp   (rule 4)
     
         NUM         shift, and go to state 1
     
         exp         go to state 11
</pre>
   <p>As was announced in beginning of the report, `<samp><span class="samp">State 8 conflicts:
1 shift/reduce</span></samp>':

<pre class="example">     state 8
     
         exp  -&gt;  exp . '+' exp   (rule 1)
         exp  -&gt;  exp '+' exp .   (rule 1)
         exp  -&gt;  exp . '-' exp   (rule 2)
         exp  -&gt;  exp . '*' exp   (rule 3)
         exp  -&gt;  exp . '/' exp   (rule 4)
     
         '*'         shift, and go to state 6
         '/'         shift, and go to state 7
     
         '/'         [reduce using rule 1 (exp)]
         $default    reduce using rule 1 (exp)
</pre>
   <p>Indeed, there are two actions associated to the lookahead `<samp><span class="samp">/</span></samp>':
either shifting (and going to state 7), or reducing rule 1.  The
conflict means that either the grammar is ambiguous, or the parser lacks
information to make the right decision.  Indeed the grammar is
ambiguous, as, since we did not specify the precedence of `<samp><span class="samp">/</span></samp>', the
sentence `<samp><span class="samp">NUM + NUM / NUM</span></samp>' can be parsed as `<samp><span class="samp">NUM + (NUM /
NUM)</span></samp>', which corresponds to shifting `<samp><span class="samp">/</span></samp>', or as `<samp><span class="samp">(NUM + NUM) /
NUM</span></samp>', which corresponds to reducing rule 1.

   <p>Because in <acronym>LALR</acronym>(1) parsing a single decision can be made, Bison
arbitrarily chose to disable the reduction, see <a href="#Shift_002fReduce">Shift/Reduce Conflicts</a>.  Discarded actions are reported in between
square brackets.

   <p>Note that all the previous states had a single possible action: either
shifting the next token and going to the corresponding state, or
reducing a single rule.  In the other cases, i.e., when shifting
<em>and</em> reducing is possible or when <em>several</em> reductions are
possible, the lookahead is required to select the action.  State 8 is
one such state: if the lookahead is `<samp><span class="samp">*</span></samp>' or `<samp><span class="samp">/</span></samp>' then the action
is shifting, otherwise the action is reducing rule 1.  In other words,
the first two items, corresponding to rule 1, are not eligible when the
lookahead is `<samp><span class="samp">*</span></samp>', since we specified that `<samp><span class="samp">*</span></samp>' has higher
precedence that `<samp><span class="samp">+</span></samp>'.  More generally, some items are eligible only
with some set of possible lookaheads.  When run with
<samp><span class="option">--report=lookahead</span></samp>, Bison specifies these lookaheads:

<pre class="example">     state 8
     
         exp  -&gt;  exp . '+' exp  [$, '+', '-', '/']   (rule 1)
         exp  -&gt;  exp '+' exp .  [$, '+', '-', '/']   (rule 1)
         exp  -&gt;  exp . '-' exp   (rule 2)
         exp  -&gt;  exp . '*' exp   (rule 3)
         exp  -&gt;  exp . '/' exp   (rule 4)
     
         '*'         shift, and go to state 6
         '/'         shift, and go to state 7
     
         '/'         [reduce using rule 1 (exp)]
         $default    reduce using rule 1 (exp)
</pre>
   <p>The remaining states are similar:

<pre class="example">     state 9
     
         exp  -&gt;  exp . '+' exp   (rule 1)
         exp  -&gt;  exp . '-' exp   (rule 2)
         exp  -&gt;  exp '-' exp .   (rule 2)
         exp  -&gt;  exp . '*' exp   (rule 3)
         exp  -&gt;  exp . '/' exp   (rule 4)
     
         '*'         shift, and go to state 6
         '/'         shift, and go to state 7
     
         '/'         [reduce using rule 2 (exp)]
         $default    reduce using rule 2 (exp)
     
     state 10
     
         exp  -&gt;  exp . '+' exp   (rule 1)
         exp  -&gt;  exp . '-' exp   (rule 2)
         exp  -&gt;  exp . '*' exp   (rule 3)
         exp  -&gt;  exp '*' exp .   (rule 3)
         exp  -&gt;  exp . '/' exp   (rule 4)
     
         '/'         shift, and go to state 7
     
         '/'         [reduce using rule 3 (exp)]
         $default    reduce using rule 3 (exp)
     
     state 11
     
         exp  -&gt;  exp . '+' exp   (rule 1)
         exp  -&gt;  exp . '-' exp   (rule 2)
         exp  -&gt;  exp . '*' exp   (rule 3)
         exp  -&gt;  exp . '/' exp   (rule 4)
         exp  -&gt;  exp '/' exp .   (rule 4)
     
         '+'         shift, and go to state 4
         '-'         shift, and go to state 5
         '*'         shift, and go to state 6
         '/'         shift, and go to state 7
     
         '+'         [reduce using rule 4 (exp)]
         '-'         [reduce using rule 4 (exp)]
         '*'         [reduce using rule 4 (exp)]
         '/'         [reduce using rule 4 (exp)]
         $default    reduce using rule 4 (exp)
</pre>
   <p class="noindent">Observe that state 11 contains conflicts due to the lack of precedence
of `<samp><span class="samp">/</span></samp>' wrt `<samp><span class="samp">+</span></samp>', `<samp><span class="samp">-</span></samp>', and `<samp><span class="samp">*</span></samp>', but also because the
associativity of `<samp><span class="samp">/</span></samp>' is not specified.

<div class="node">
<p><hr>
<a name="Tracing"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Understanding">Understanding</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Debugging">Debugging</a>

</div>

<h3 class="section">8.2 Tracing Your Parser</h3>

<p><a name="index-yydebug-277"></a><a name="index-debugging-278"></a><a name="index-tracing-the-parser-279"></a>
If a Bison grammar compiles properly but doesn't do what you want when it
runs, the <code>yydebug</code> parser-trace feature can help you figure out why.

   <p>There are several means to enable compilation of trace facilities:

     <dl>
<dt>the macro <code>YYDEBUG</code><dd><a name="index-YYDEBUG-280"></a>Define the macro <code>YYDEBUG</code> to a nonzero value when you compile the
parser.  This is compliant with <acronym>POSIX</acronym> Yacc.  You could use
`<samp><span class="samp">-DYYDEBUG=1</span></samp>' as a compiler option or you could put `<samp><span class="samp">#define
YYDEBUG 1</span></samp>' in the prologue of the grammar file (see <a href="#Prologue">The Prologue</a>).

     <br><dt>the option <samp><span class="option">-t</span></samp>, <samp><span class="option">--debug</span></samp><dd>Use the `<samp><span class="samp">-t</span></samp>' option when you run Bison (see <a href="#Invocation">Invoking Bison</a>).  This is <acronym>POSIX</acronym> compliant too.

     <br><dt>the directive `<samp><span class="samp">%debug</span></samp>'<dd><a name="index-g_t_0025debug-281"></a>Add the <code>%debug</code> directive (see <a href="#Decl-Summary">Bison Declaration Summary</a>).  This is a Bison extension, which will prove
useful when Bison will output parsers for languages that don't use a
preprocessor.  Unless <acronym>POSIX</acronym> and Yacc portability matter to
you, this is
the preferred solution. 
</dl>

   <p>We suggest that you always enable the debug option so that debugging is
always possible.

   <p>The trace facility outputs messages with macro calls of the form
<code>YYFPRINTF (stderr, </code><var>format</var><code>, </code><var>args</var><code>)</code> where
<var>format</var> and <var>args</var> are the usual <code>printf</code> format and
arguments.  If you define <code>YYDEBUG</code> to a nonzero value but do not
define <code>YYFPRINTF</code>, <code>&lt;stdio.h&gt;</code> is automatically included
and <code>YYPRINTF</code> is defined to <code>fprintf</code>.

   <p>Once you have compiled the program with trace facilities, the way to
request a trace is to store a nonzero value in the variable <code>yydebug</code>. 
You can do this by making the C code do it (in <code>main</code>, perhaps), or
you can alter the value with a C debugger.

   <p>Each step taken by the parser when <code>yydebug</code> is nonzero produces a
line or two of trace information, written on <code>stderr</code>.  The trace
messages tell you these things:

     <ul>
<li>Each time the parser calls <code>yylex</code>, what kind of token was read.

     <li>Each time a token is shifted, the depth and complete contents of the
state stack (see <a href="#Parser-States">Parser States</a>).

     <li>Each time a rule is reduced, which rule it is, and the complete contents
of the state stack afterward. 
</ul>

   <p>To make sense of this information, it helps to refer to the listing file
produced by the Bison `<samp><span class="samp">-v</span></samp>' option (see <a href="#Invocation">Invoking Bison</a>).  This file shows the meaning of each state in terms of
positions in various rules, and also what each state will do with each
possible input token.  As you read the successive trace messages, you
can see that the parser is functioning according to its specification in
the listing file.  Eventually you will arrive at the place where
something undesirable happens, and you will see which parts of the
grammar are to blame.

   <p>The parser file is a C program and you can use C debuggers on it, but it's
not easy to interpret what it is doing.  The parser function is a
finite-state machine interpreter, and aside from the actions it executes
the same code over and over.  Only the values of variables show where in
the grammar it is working.

   <p><a name="index-YYPRINT-282"></a>The debugging information normally gives the token type of each token
read, but not its semantic value.  You can optionally define a macro
named <code>YYPRINT</code> to provide a way to print the value.  If you define
<code>YYPRINT</code>, it should take three arguments.  The parser will pass a
standard I/O stream, the numeric code for the token type, and the token
value (from <code>yylval</code>).

   <p>Here is an example of <code>YYPRINT</code> suitable for the multi-function
calculator (see <a href="#Mfcalc-Decl">Declarations for <code>mfcalc</code></a>):

<pre class="smallexample">     %{
       static void print_token_value (FILE *, int, YYSTYPE);
       #define YYPRINT(file, type, value) print_token_value (file, type, value)
     %}
     
     ... %% ... %% ...
     
     static void
     print_token_value (FILE *file, int type, YYSTYPE value)
     {
       if (type == VAR)
         fprintf (file, "%s", value.tptr-&gt;name);
       else if (type == NUM)
         fprintf (file, "%d", value.val);
     }
</pre>
   <!-- ================================================= Invoking Bison -->
<div class="node">
<p><hr>
<a name="Invocation"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Table-of-Symbols">Table of Symbols</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Debugging">Debugging</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="chapter">9 Invoking Bison</h2>

<p><a name="index-invoking-Bison-283"></a><a name="index-Bison-invocation-284"></a><a name="index-options-for-invoking-Bison-285"></a>
The usual way to invoke Bison is as follows:

<pre class="example">     bison <var>infile</var>
</pre>
   <p>Here <var>infile</var> is the grammar file name, which usually ends in
`<samp><span class="samp">.y</span></samp>'.  The parser file's name is made by replacing the `<samp><span class="samp">.y</span></samp>'
with `<samp><span class="samp">.tab.c</span></samp>'.  Thus, the `<samp><span class="samp">bison foo.y</span></samp>' filename yields
<samp><span class="file">foo.tab.c</span></samp>, and the `<samp><span class="samp">bison hack/foo.y</span></samp>' filename yields
<samp><span class="file">hack/foo.tab.c</span></samp>.  It's also possible, in case you are writing
C++ code instead of C in your grammar file, to name it <samp><span class="file">foo.ypp</span></samp>
or <samp><span class="file">foo.y++</span></samp>.  Then, the output files will take an extension like
the given one as input (respectively <samp><span class="file">foo.tab.cpp</span></samp> and
<samp><span class="file">foo.tab.c++</span></samp>). 
This feature takes effect with all options that manipulate filenames like
`<samp><span class="samp">-o</span></samp>' or `<samp><span class="samp">-d</span></samp>'.

   <p>For example :

<pre class="example">     bison -d <var>infile.yxx</var>
</pre>
   <p class="noindent">will produce <samp><span class="file">infile.tab.cxx</span></samp> and <samp><span class="file">infile.tab.hxx</span></samp>, and

<pre class="example">     bison -d -o <var>output.c++</var> <var>infile.y</var>
</pre>
   <p class="noindent">will produce <samp><span class="file">output.c++</span></samp> and <samp><span class="file">outfile.h++</span></samp>.

   <p>For compatibility with <acronym>POSIX</acronym>, the standard Bison
distribution also contains a shell script called <samp><span class="command">yacc</span></samp> that
invokes Bison with the <samp><span class="option">-y</span></samp> option.

<ul class="menu">
<li><a accesskey="1" href="#Bison-Options">Bison Options</a>:      All the options described in detail,
                        in alphabetical order by short options. 
<li><a accesskey="2" href="#Option-Cross-Key">Option Cross Key</a>:   Alphabetical list of long options. 
<li><a accesskey="3" href="#Yacc-Library">Yacc Library</a>:       Yacc-compatible <code>yylex</code> and <code>main</code>. 
</ul>

<div class="node">
<p><hr>
<a name="Bison-Options"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Option-Cross-Key">Option Cross Key</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Invocation">Invocation</a>

</div>

<h3 class="section">9.1 Bison Options</h3>

<p>Bison supports both traditional single-letter options and mnemonic long
option names.  Long option names are indicated with `<samp><span class="samp">--</span></samp>' instead of
`<samp><span class="samp">-</span></samp>'.  Abbreviations for option names are allowed as long as they
are unique.  When a long option takes an argument, like
`<samp><span class="samp">--file-prefix</span></samp>', connect the option name and the argument with
`<samp><span class="samp">=</span></samp>'.

   <p>Here is a list of options that can be used with Bison, alphabetized by
short option.  It is followed by a cross key alphabetized by long
option.

<!-- Please, keep this ordered as in `bison -help'. -->
<p class="noindent">Operations modes:
     <dl>
<dt><samp><span class="option">-h</span></samp><dt><samp><span class="option">--help</span></samp><dd>Print a summary of the command-line options to Bison and exit.

     <br><dt><samp><span class="option">-V</span></samp><dt><samp><span class="option">--version</span></samp><dd>Print the version number of Bison and exit.

     <br><dt><samp><span class="option">-y</span></samp><dt><samp><span class="option">--yacc</span></samp><dd>Equivalent to `<samp><span class="samp">-o y.tab.c</span></samp>'; the parser output file is called
<samp><span class="file">y.tab.c</span></samp>, and the other outputs are called <samp><span class="file">y.output</span></samp> and
<samp><span class="file">y.tab.h</span></samp>.  The purpose of this option is to imitate Yacc's output
file name conventions.  Thus, the following shell script can substitute
for Yacc, and the Bison distribution contains such a script for
compatibility with <acronym>POSIX</acronym>:

     <pre class="example">          #! /bin/sh
          bison -y "$&uml;
     </pre>
     </dl>

<p class="noindent">Tuning the parser:

     <dl>
<dt><samp><span class="option">-S </span><var>file</var></samp><dt><samp><span class="option">--skeleton=</span><var>file</var></samp><dd>Specify the skeleton to use.  You probably don't need this option unless
you are developing Bison.

     <br><dt><samp><span class="option">-t</span></samp><dt><samp><span class="option">--debug</span></samp><dd>In the parser file, define the macro <code>YYDEBUG</code> to 1 if it is not
already defined, so that the debugging facilities are compiled. 
See <a href="#Tracing">Tracing Your Parser</a>.

     <br><dt><samp><span class="option">--locations</span></samp><dd>Pretend that <code>%locations</code> was specified.  See <a href="#Decl-Summary">Decl Summary</a>.

     <br><dt><samp><span class="option">-p </span><var>prefix</var></samp><dt><samp><span class="option">--name-prefix=</span><var>prefix</var></samp><dd>Pretend that <code>%name-prefix="</code><var>prefix</var><code>"</code> was specified. 
See <a href="#Decl-Summary">Decl Summary</a>.

     <br><dt><samp><span class="option">-l</span></samp><dt><samp><span class="option">--no-lines</span></samp><dd>Don't put any <code>#line</code> preprocessor commands in the parser file. 
Ordinarily Bison puts them in the parser file so that the C compiler
and debuggers will associate errors with your source file, the
grammar file.  This option causes them to associate errors with the
parser file, treating it as an independent source file in its own right.

     <br><dt><samp><span class="option">-n</span></samp><dt><samp><span class="option">--no-parser</span></samp><dd>Pretend that <code>%no-parser</code> was specified.  See <a href="#Decl-Summary">Decl Summary</a>.

     <br><dt><samp><span class="option">-k</span></samp><dt><samp><span class="option">--token-table</span></samp><dd>Pretend that <code>%token-table</code> was specified.  See <a href="#Decl-Summary">Decl Summary</a>. 
</dl>

<p class="noindent">Adjust the output:

     <dl>
<dt><samp><span class="option">-d</span></samp><dt><samp><span class="option">--defines</span></samp><dd>Pretend that <code>%defines</code> was specified, i.e., write an extra output
file containing macro definitions for the token type names defined in
the grammar and the semantic value type <code>YYSTYPE</code>, as well as a few
<code>extern</code> variable declarations.  See <a href="#Decl-Summary">Decl Summary</a>.

     <br><dt><samp><span class="option">--defines=</span><var>defines-file</var></samp><dd>Same as above, but save in the file <var>defines-file</var>.

     <br><dt><samp><span class="option">-b </span><var>file-prefix</var></samp><dt><samp><span class="option">--file-prefix=</span><var>prefix</var></samp><dd>Pretend that <code>%verbose</code> was specified, i.e, specify prefix to use
for all Bison output file names.  See <a href="#Decl-Summary">Decl Summary</a>.

     <br><dt><samp><span class="option">-r </span><var>things</var></samp><dt><samp><span class="option">--report=</span><var>things</var></samp><dd>Write an extra output file containing verbose description of the comma
separated list of <var>things</var> among:

          <dl>
<dt><code>state</code><dd>Description of the grammar, conflicts (resolved and unresolved), and
<acronym>LALR</acronym> automaton.

          <br><dt><code>lookahead</code><dd>Implies <code>state</code> and augments the description of the automaton with
each rule's lookahead set.

          <br><dt><code>itemset</code><dd>Implies <code>state</code> and augments the description of the automaton with
the full set of items for each state, instead of its core only. 
</dl>

     <p>For instance, on the following grammar

     <br><dt><samp><span class="option">-v</span></samp><dt><samp><span class="option">--verbose</span></samp><dd>Pretend that <code>%verbose</code> was specified, i.e, write an extra output
file containing verbose descriptions of the grammar and
parser.  See <a href="#Decl-Summary">Decl Summary</a>.

     <br><dt><samp><span class="option">-o </span><var>filename</var></samp><dt><samp><span class="option">--output=</span><var>filename</var></samp><dd>Specify the <var>filename</var> for the parser file.

     <p>The other output files' names are constructed from <var>filename</var> as
described under the `<samp><span class="samp">-v</span></samp>' and `<samp><span class="samp">-d</span></samp>' options.

     <br><dt><samp><span class="option">-g</span></samp><dd>Output a <acronym>VCG</acronym> definition of the <acronym>LALR</acronym>(1) grammar
automaton computed by Bison.  If the grammar file is <samp><span class="file">foo.y</span></samp>, the
<acronym>VCG</acronym> output file will
be <samp><span class="file">foo.vcg</span></samp>.

     <br><dt><samp><span class="option">--graph=</span><var>graph-file</var></samp><dd>The behavior of <var>&ndash;graph</var> is the same than `<samp><span class="samp">-g</span></samp>'.  The only
difference is that it has an optional argument which is the name of
the output graph filename. 
</dl>

<div class="node">
<p><hr>
<a name="Option-Cross-Key"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Yacc-Library">Yacc Library</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Bison-Options">Bison Options</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Invocation">Invocation</a>

</div>

<h3 class="section">9.2 Option Cross Key</h3>

<p>Here is a list of options, alphabetized by long option, to help you find
the corresponding short option.

<div class="node">
<p><hr>
<a name="Yacc-Library"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Option-Cross-Key">Option Cross Key</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Invocation">Invocation</a>

</div>

<h3 class="section">9.3 Yacc Library</h3>

<p>The Yacc library contains default implementations of the
<code>yyerror</code> and <code>main</code> functions.  These default
implementations are normally not useful, but <acronym>POSIX</acronym> requires
them.  To use the Yacc library, link your program with the
<samp><span class="option">-ly</span></samp> option.  Note that Bison's implementation of the Yacc
library is distributed under the terms of the <acronym>GNU</acronym> General
Public License (see <a href="#Copying">Copying</a>).

   <p>If you use the Yacc library's <code>yyerror</code> function, you should
declare <code>yyerror</code> as follows:

<pre class="example">     int yyerror (char const *);
</pre>
   <p>Bison ignores the <code>int</code> value returned by this <code>yyerror</code>. 
If you use the Yacc library's <code>main</code> function, your
<code>yyparse</code> function should have the following type signature:

<pre class="example">     int yyparse (void);
</pre>
   <!-- ================================================= Invoking Bison -->
<div class="node">
<p><hr>
<a name="FAQ"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Copying-This-Manual">Copying This Manual</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Glossary">Glossary</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="chapter">10 Frequently Asked Questions</h2>

<p><a name="index-frequently-asked-questions-286"></a><a name="index-questions-287"></a>
Several questions about Bison come up occasionally.  Here some of them
are addressed.

<ul class="menu">
<li><a accesskey="1" href="#Parser-Stack-Overflow">Parser Stack Overflow</a>:       Breaking the Stack Limits
</ul>

<div class="node">
<p><hr>
<a name="Parser-Stack-Overflow"></a>
Up:&nbsp;<a rel="up" accesskey="u" href="#FAQ">FAQ</a>

</div>

<h3 class="section">10.1 Parser Stack Overflow</h3>

<pre class="display">     My parser returns with error with a `<samp><span class="samp">parser stack overflow</span></samp>'
     message.  What can I do?
</pre>
   <p>This question is already addressed elsewhere, See <a href="#Recursion">Recursive Rules</a>.

<!-- ================================================= Table of Symbols -->
<div class="node">
<p><hr>
<a name="Table-of-Symbols"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Glossary">Glossary</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Invocation">Invocation</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="appendix">Appendix A Bison Symbols</h2>

<p><a name="index-Bison-symbols_002c-table-of-288"></a><a name="index-symbols-in-Bison_002c-table-of-289"></a>

<div class="defun">
&mdash; Variable: <b>@$</b><var><a name="index-g_t_0040_0040_0024-290"></a></var><br>
<blockquote><p>In an action, the location of the left-hand side of the rule. 
See <a href="#Locations">Locations Overview</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Variable: <b>@</b><var>n</var><var><a name="index-g_t_0040_0040_0040var_007bn_007d-291"></a></var><br>
<blockquote><p>In an action, the location of the <var>n</var>-th symbol of the right-hand
side of the rule.  See <a href="#Locations">Locations Overview</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Variable: <b>$$</b><var><a name="index-g_t_0024_0024-292"></a></var><br>
<blockquote><p>In an action, the semantic value of the left-hand side of the rule. 
See <a href="#Actions">Actions</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Variable: <b>$</b><var>n<a name="index-g_t_0024-293"></a></var><br>
<blockquote><p>In an action, the semantic value of the <var>n</var>-th symbol of the
right-hand side of the rule.  See <a href="#Actions">Actions</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Symbol: <b>$accept</b><var><a name="index-g_t_0024accept-294"></a></var><br>
<blockquote><p>The predefined nonterminal whose only rule is `<samp><span class="samp">$accept: </span><var>start</var><span class="samp">
$end</span></samp>', where <var>start</var> is the start symbol.  See <a href="#Start-Decl">The Start-Symbol</a>.  It cannot be used in the grammar. 
</p></blockquote></div>

<div class="defun">
&mdash; Symbol: <b>$end</b><var><a name="index-g_t_0024end-295"></a></var><br>
<blockquote><p>The predefined token marking the end of the token stream.  It cannot be
used in the grammar. 
</p></blockquote></div>

<div class="defun">
&mdash; Symbol: <b>$undefined</b><var><a name="index-g_t_0024undefined-296"></a></var><br>
<blockquote><p>The predefined token onto which all undefined values returned by
<code>yylex</code> are mapped.  It cannot be used in the grammar, rather, use
<code>error</code>. 
</p></blockquote></div>

<div class="defun">
&mdash; Symbol: <b>error</b><var><a name="index-error-297"></a></var><br>
<blockquote><p>A token name reserved for error recovery.  This token may be used in
grammar rules so as to allow the Bison parser to recognize an error in
the grammar without halting the process.  In effect, a sentence
containing an error may be recognized as valid.  On a syntax error, the
token <code>error</code> becomes the current look-ahead token.  Actions
corresponding to <code>error</code> are then executed, and the look-ahead
token is reset to the token that originally caused the violation. 
See <a href="#Error-Recovery">Error Recovery</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYABORT</b><var><a name="index-YYABORT-298"></a></var><br>
<blockquote><p>Macro to pretend that an unrecoverable syntax error has occurred, by
making <code>yyparse</code> return 1 immediately.  The error reporting
function <code>yyerror</code> is not called.  See <a href="#Parser-Function">The Parser Function <code>yyparse</code></a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYACCEPT</b><var><a name="index-YYACCEPT-299"></a></var><br>
<blockquote><p>Macro to pretend that a complete utterance of the language has been
read, by making <code>yyparse</code> return 0 immediately. 
See <a href="#Parser-Function">The Parser Function <code>yyparse</code></a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYBACKUP</b><var><a name="index-YYBACKUP-300"></a></var><br>
<blockquote><p>Macro to discard a value from the parser stack and fake a look-ahead
token.  See <a href="#Action-Features">Special Features for Use in Actions</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYDEBUG</b><var><a name="index-YYDEBUG-301"></a></var><br>
<blockquote><p>Macro to define to equip the parser with tracing code.  See <a href="#Tracing">Tracing Your Parser</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYERROR</b><var><a name="index-YYERROR-302"></a></var><br>
<blockquote><p>Macro to pretend that a syntax error has just been detected: call
<code>yyerror</code> and then perform normal error recovery if possible
(see <a href="#Error-Recovery">Error Recovery</a>), or (if recovery is impossible) make
<code>yyparse</code> return 1.  See <a href="#Error-Recovery">Error Recovery</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYERROR_VERBOSE</b><var><a name="index-YYERROR_005fVERBOSE-303"></a></var><br>
<blockquote><p>An obsolete macro that you define with <code>#define</code> in the prologue
to request verbose, specific error message strings
when <code>yyerror</code> is called.  It doesn't matter what definition you
use for <code>YYERROR_VERBOSE</code>, just whether you define it.  Using
<code>%error-verbose</code> is preferred. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYINITDEPTH</b><var><a name="index-YYINITDEPTH-304"></a></var><br>
<blockquote><p>Macro for specifying the initial size of the parser stack. 
See <a href="#Stack-Overflow">Stack Overflow</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYLEX_PARAM</b><var><a name="index-YYLEX_005fPARAM-305"></a></var><br>
<blockquote><p>An obsolete macro for specifying an extra argument (or list of extra
arguments) for <code>yyparse</code> to pass to <code>yylex</code>.  he use of this
macro is deprecated, and is supported only for Yacc like parsers. 
See <a href="#Pure-Calling">Calling Conventions for Pure Parsers</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Type: <b>YYLTYPE</b><var><a name="index-YYLTYPE-306"></a></var><br>
<blockquote><p>Data type of <code>yylloc</code>; by default, a structure with four
members.  See <a href="#Location-Type">Data Types of Locations</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYMAXDEPTH</b><var><a name="index-YYMAXDEPTH-307"></a></var><br>
<blockquote><p>Macro for specifying the maximum size of the parser stack.  See <a href="#Stack-Overflow">Stack Overflow</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYPARSE_PARAM</b><var><a name="index-YYPARSE_005fPARAM-308"></a></var><br>
<blockquote><p>An obsolete macro for specifying the name of a parameter that
<code>yyparse</code> should accept.  The use of this macro is deprecated, and
is supported only for Yacc like parsers.  See <a href="#Pure-Calling">Calling Conventions for Pure Parsers</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYRECOVERING</b><var><a name="index-YYRECOVERING-309"></a></var><br>
<blockquote><p>Macro whose value indicates whether the parser is recovering from a
syntax error.  See <a href="#Action-Features">Special Features for Use in Actions</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>YYSTACK_USE_ALLOCA</b><var><a name="index-YYSTACK_005fUSE_005fALLOCA-310"></a></var><br>
<blockquote><p>Macro used to control the use of <code>alloca</code>.  If defined to `<samp><span class="samp">0</span></samp>',
the parser will not use <code>alloca</code> but <code>malloc</code> when trying to
grow its internal stacks.  Do <em>not</em> define <code>YYSTACK_USE_ALLOCA</code>
to anything else. 
</p></blockquote></div>

<div class="defun">
&mdash; Type: <b>YYSTYPE</b><var><a name="index-YYSTYPE-311"></a></var><br>
<blockquote><p>Data type of semantic values; <code>int</code> by default. 
See <a href="#Value-Type">Data Types of Semantic Values</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Variable: <b>yychar</b><var><a name="index-yychar-312"></a></var><br>
<blockquote><p>External integer variable that contains the integer value of the current
look-ahead token.  (In a pure parser, it is a local variable within
<code>yyparse</code>.)  Error-recovery rule actions may examine this variable. 
See <a href="#Action-Features">Special Features for Use in Actions</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Variable: <b>yyclearin</b><var><a name="index-yyclearin-313"></a></var><br>
<blockquote><p>Macro used in error-recovery rule actions.  It clears the previous
look-ahead token.  See <a href="#Error-Recovery">Error Recovery</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Variable: <b>yydebug</b><var><a name="index-yydebug-314"></a></var><br>
<blockquote><p>External integer variable set to zero by default.  If <code>yydebug</code>
is given a nonzero value, the parser will output information on input
symbols and parser action.  See <a href="#Tracing">Tracing Your Parser</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Macro: <b>yyerrok</b><var><a name="index-yyerrok-315"></a></var><br>
<blockquote><p>Macro to cause parser to recover immediately to its normal mode
after a syntax error.  See <a href="#Error-Recovery">Error Recovery</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Function: <b>yyerror</b><var><a name="index-yyerror-316"></a></var><br>
<blockquote><p>User-supplied function to be called by <code>yyparse</code> on error. 
See <a href="#Error-Reporting">The Error Reporting Function <code>yyerror</code></a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Function: <b>yylex</b><var><a name="index-yylex-317"></a></var><br>
<blockquote><p>User-supplied lexical analyzer function, called with no arguments to get
the next token.  See <a href="#Lexical">The Lexical Analyzer Function <code>yylex</code></a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Variable: <b>yylval</b><var><a name="index-yylval-318"></a></var><br>
<blockquote><p>External variable in which <code>yylex</code> should place the semantic
value associated with a token.  (In a pure parser, it is a local
variable within <code>yyparse</code>, and its address is passed to
<code>yylex</code>.)  See <a href="#Token-Values">Semantic Values of Tokens</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Variable: <b>yylloc</b><var><a name="index-yylloc-319"></a></var><br>
<blockquote><p>External variable in which <code>yylex</code> should place the line and column
numbers associated with a token.  (In a pure parser, it is a local
variable within <code>yyparse</code>, and its address is passed to
<code>yylex</code>.)  You can ignore this variable if you don't use the
`<samp><span class="samp">@</span></samp>' feature in the grammar actions.  See <a href="#Token-Positions">Textual Positions of Tokens</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Variable: <b>yynerrs</b><var><a name="index-yynerrs-320"></a></var><br>
<blockquote><p>Global variable which Bison increments each time there is a syntax error. 
(In a pure parser, it is a local variable within <code>yyparse</code>.) 
See <a href="#Error-Reporting">The Error Reporting Function <code>yyerror</code></a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Function: <b>yyparse</b><var><a name="index-yyparse-321"></a></var><br>
<blockquote><p>The parser function produced by Bison; call this function to start
parsing.  See <a href="#Parser-Function">The Parser Function <code>yyparse</code></a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%debug</b><var><a name="index-g_t_0025debug-322"></a></var><br>
<blockquote><p>Equip the parser for debugging.  See <a href="#Decl-Summary">Decl Summary</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%defines</b><var><a name="index-g_t_0025defines-323"></a></var><br>
<blockquote><p>Bison declaration to create a header file meant for the scanner. 
See <a href="#Decl-Summary">Decl Summary</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%destructor</b><var><a name="index-g_t_0025destructor-324"></a></var><br>
<blockquote><p>Specifying how the parser should reclaim the memory associated to
discarded symbols. See <a href="#Destructor-Decl">Freeing Discarded Symbols</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%dprec</b><var><a name="index-g_t_0025dprec-325"></a></var><br>
<blockquote><p>Bison declaration to assign a precedence to a rule that is used at parse
time to resolve reduce/reduce conflicts.  See <a href="#GLR-Parsers">Writing <acronym>GLR</acronym> Parsers</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%error-verbose</b><var><a name="index-g_t_0025error_002dverbose-326"></a></var><br>
<blockquote><p>Bison declaration to request verbose, specific error message strings
when <code>yyerror</code> is called. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%file-prefix="</b><var>prefix"<a name="index-g_t_0025file_002dprefix_003d_0022-327"></a></var><br>
<blockquote><p>Bison declaration to set the prefix of the output files.  See <a href="#Decl-Summary">Decl Summary</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%glr-parser</b><var><a name="index-g_t_0025glr_002dparser-328"></a></var><br>
<blockquote><p>Bison declaration to produce a <acronym>GLR</acronym> parser.  See <a href="#GLR-Parsers">Writing <acronym>GLR</acronym> Parsers</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%left</b><var><a name="index-g_t_0025left-329"></a></var><br>
<blockquote><p>Bison declaration to assign left associativity to token(s). 
See <a href="#Precedence-Decl">Operator Precedence</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%merge</b><var><a name="index-g_t_0025merge-330"></a></var><br>
<blockquote><p>Bison declaration to assign a merging function to a rule.  If there is a
reduce/reduce conflict with a rule having the same merging function, the
function is applied to the two semantic values to get a single result. 
See <a href="#GLR-Parsers">Writing <acronym>GLR</acronym> Parsers</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%name-prefix="</b><var>prefix"<a name="index-g_t_0025name_002dprefix_003d_0022-331"></a></var><br>
<blockquote><p>Bison declaration to rename the external symbols.  See <a href="#Decl-Summary">Decl Summary</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%no-lines</b><var><a name="index-g_t_0025no_002dlines-332"></a></var><br>
<blockquote><p>Bison declaration to avoid generating <code>#line</code> directives in the
parser file.  See <a href="#Decl-Summary">Decl Summary</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%nonassoc</b><var><a name="index-g_t_0025nonassoc-333"></a></var><br>
<blockquote><p>Bison declaration to assign non-associativity to token(s). 
See <a href="#Precedence-Decl">Operator Precedence</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%output="</b><var>filename"<a name="index-g_t_0025output_003d_0022-334"></a></var><br>
<blockquote><p>Bison declaration to set the name of the parser file.  See <a href="#Decl-Summary">Decl Summary</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%prec</b><var><a name="index-g_t_0025prec-335"></a></var><br>
<blockquote><p>Bison declaration to assign a precedence to a specific rule. 
See <a href="#Contextual-Precedence">Context-Dependent Precedence</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%pure-parser</b><var><a name="index-g_t_0025pure_002dparser-336"></a></var><br>
<blockquote><p>Bison declaration to request a pure (reentrant) parser. 
See <a href="#Pure-Decl">A Pure (Reentrant) Parser</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%right</b><var><a name="index-g_t_0025right-337"></a></var><br>
<blockquote><p>Bison declaration to assign right associativity to token(s). 
See <a href="#Precedence-Decl">Operator Precedence</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%start</b><var><a name="index-g_t_0025start-338"></a></var><br>
<blockquote><p>Bison declaration to specify the start symbol.  See <a href="#Start-Decl">The Start-Symbol</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%token</b><var><a name="index-g_t_0025token-339"></a></var><br>
<blockquote><p>Bison declaration to declare token(s) without specifying precedence. 
See <a href="#Token-Decl">Token Type Names</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%token-table</b><var><a name="index-g_t_0025token_002dtable-340"></a></var><br>
<blockquote><p>Bison declaration to include a token name table in the parser file. 
See <a href="#Decl-Summary">Decl Summary</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%type</b><var><a name="index-g_t_0025type-341"></a></var><br>
<blockquote><p>Bison declaration to declare nonterminals.  See <a href="#Type-Decl">Nonterminal Symbols</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Directive: <b>%union</b><var><a name="index-g_t_0025union-342"></a></var><br>
<blockquote><p>Bison declaration to specify several possible data types for semantic
values.  See <a href="#Union-Decl">The Collection of Value Types</a>. 
</p></blockquote></div>

   <pre class="sp">

</pre>

These are the punctuation and delimiters used in Bison input:

<div class="defun">
&mdash; Delimiter: <b>%%</b><var><a name="index-g_t_0025_0025-343"></a></var><br>
<blockquote><p>Delimiter used to separate the grammar rule section from the
Bison declarations section or the epilogue. 
See <a href="#Grammar-Layout">The Overall Layout of a Bison Grammar</a>. 
</p></blockquote></div>

<!-- Don't insert spaces, or check the DVI output. -->
<div class="defun">
&mdash; Delimiter: <b>%</b><var>{code%}<a name="index-g_t_0025-344"></a></var><br>
<blockquote><p>All code listed between `<samp><span class="samp">%{</span></samp>' and `<samp><span class="samp">%}</span></samp>' is copied directly to
the output file uninterpreted.  Such code forms the prologue of the input
file.  See <a href="#Grammar-Outline">Outline of a Bison Grammar</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Construct: <b>/*</b><var><small class="dots">...</small>*/<a name="index-g_t_002f_002a-345"></a></var><br>
<blockquote><p>Comment delimiters, as in C. 
</p></blockquote></div>

<div class="defun">
&mdash; Delimiter: <b>:</b><var><a name="index-g_t_003a-346"></a></var><br>
<blockquote><p>Separates a rule's result from its components.  See <a href="#Rules">Syntax of Grammar Rules</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Delimiter: <b>;</b><var><a name="index-g_t_003b-347"></a></var><br>
<blockquote><p>Terminates a rule.  See <a href="#Rules">Syntax of Grammar Rules</a>. 
</p></blockquote></div>

<div class="defun">
&mdash; Delimiter: <b>|</b><var><a name="index-g_t_007c-348"></a></var><br>
<blockquote><p>Separates alternate rules for the same result nonterminal. 
See <a href="#Rules">Syntax of Grammar Rules</a>. 
</p></blockquote></div>

<div class="node">
<p><hr>
<a name="Glossary"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#FAQ">FAQ</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Table-of-Symbols">Table of Symbols</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="appendix">Appendix B Glossary</h2>

<p><a name="index-glossary-349"></a>
     <dl>
<dt>Backus-Naur Form (<acronym>BNF</acronym>; also called &ldquo;Backus Normal Form&rdquo;)<dd>Formal method of specifying context-free grammars originally proposed
by John Backus, and slightly improved by Peter Naur in his 1960-01-02
committee document contributing to what became the Algol 60 report. 
See <a href="#Language-and-Grammar">Languages and Context-Free Grammars</a>.

     <br><dt>Context-free grammars<dd>Grammars specified as rules that can be applied regardless of context. 
Thus, if there is a rule which says that an integer can be used as an
expression, integers are allowed <em>anywhere</em> an expression is
permitted.  See <a href="#Language-and-Grammar">Languages and Context-Free Grammars</a>.

     <br><dt>Dynamic allocation<dd>Allocation of memory that occurs during execution, rather than at
compile time or on entry to a function.

     <br><dt>Empty string<dd>Analogous to the empty set in set theory, the empty string is a
character string of length zero.

     <br><dt>Finite-state stack machine<dd>A &ldquo;machine&rdquo; that has discrete states in which it is said to exist at
each instant in time.  As input to the machine is processed, the
machine moves from state to state as specified by the logic of the
machine.  In the case of the parser, the input is the language being
parsed, and the states correspond to various stages in the grammar
rules.  See <a href="#Algorithm">The Bison Parser Algorithm</a>.

     <br><dt>Generalized <acronym>LR</acronym> (<acronym>GLR</acronym>)<dd>A parsing algorithm that can handle all context-free grammars, including those
that are not <acronym>LALR</acronym>(1).  It resolves situations that Bison's
usual <acronym>LALR</acronym>(1)
algorithm cannot by effectively splitting off multiple parsers, trying all
possible parsers, and discarding those that fail in the light of additional
right context.  See <a href="#Generalized-LR-Parsing">Generalized <acronym>LR</acronym> Parsing</a>.

     <br><dt>Grouping<dd>A language construct that is (in general) grammatically divisible;
for example, `expression' or `declaration' in C. 
See <a href="#Language-and-Grammar">Languages and Context-Free Grammars</a>.

     <br><dt>Infix operator<dd>An arithmetic operator that is placed between the operands on which it
performs some operation.

     <br><dt>Input stream<dd>A continuous flow of data between devices or programs.

     <br><dt>Language construct<dd>One of the typical usage schemas of the language.  For example, one of
the constructs of the C language is the <code>if</code> statement. 
See <a href="#Language-and-Grammar">Languages and Context-Free Grammars</a>.

     <br><dt>Left associativity<dd>Operators having left associativity are analyzed from left to right:
`<samp><span class="samp">a+b+c</span></samp>' first computes `<samp><span class="samp">a+b</span></samp>' and then combines with
`<samp><span class="samp">c</span></samp>'.  See <a href="#Precedence">Operator Precedence</a>.

     <br><dt>Left recursion<dd>A rule whose result symbol is also its first component symbol; for
example, `<samp><span class="samp">expseq1 : expseq1 ',' exp;</span></samp>'.  See <a href="#Recursion">Recursive Rules</a>.

     <br><dt>Left-to-right parsing<dd>Parsing a sentence of a language by analyzing it token by token from
left to right.  See <a href="#Algorithm">The Bison Parser Algorithm</a>.

     <br><dt>Lexical analyzer (scanner)<dd>A function that reads an input stream and returns tokens one by one. 
See <a href="#Lexical">The Lexical Analyzer Function <code>yylex</code></a>.

     <br><dt>Lexical tie-in<dd>A flag, set by actions in the grammar rules, which alters the way
tokens are parsed.  See <a href="#Lexical-Tie_002dins">Lexical Tie-ins</a>.

     <br><dt>Literal string token<dd>A token which consists of two or more fixed characters.  See <a href="#Symbols">Symbols</a>.

     <br><dt>Look-ahead token<dd>A token already read but not yet shifted.  See <a href="#Look_002dAhead">Look-Ahead Tokens</a>.

     <br><dt><acronym>LALR</acronym>(1)<dd>The class of context-free grammars that Bison (like most other parser
generators) can handle; a subset of <acronym>LR</acronym>(1).  See <a href="#Mystery-Conflicts">Mysterious Reduce/Reduce Conflicts</a>.

     <br><dt><acronym>LR</acronym>(1)<dd>The class of context-free grammars in which at most one token of
look-ahead is needed to disambiguate the parsing of any piece of input.

     <br><dt>Nonterminal symbol<dd>A grammar symbol standing for a grammatical construct that can
be expressed through rules in terms of smaller constructs; in other
words, a construct that is not a token.  See <a href="#Symbols">Symbols</a>.

     <br><dt>Parser<dd>A function that recognizes valid sentences of a language by analyzing
the syntax structure of a set of tokens passed to it from a lexical
analyzer.

     <br><dt>Postfix operator<dd>An arithmetic operator that is placed after the operands upon which it
performs some operation.

     <br><dt>Reduction<dd>Replacing a string of nonterminals and/or terminals with a single
nonterminal, according to a grammar rule.  See <a href="#Algorithm">The Bison Parser Algorithm</a>.

     <br><dt>Reentrant<dd>A reentrant subprogram is a subprogram which can be in invoked any
number of times in parallel, without interference between the various
invocations.  See <a href="#Pure-Decl">A Pure (Reentrant) Parser</a>.

     <br><dt>Reverse polish notation<dd>A language in which all operators are postfix operators.

     <br><dt>Right recursion<dd>A rule whose result symbol is also its last component symbol; for
example, `<samp><span class="samp">expseq1: exp ',' expseq1;</span></samp>'.  See <a href="#Recursion">Recursive Rules</a>.

     <br><dt>Semantics<dd>In computer languages, the semantics are specified by the actions
taken for each instance of the language, i.e., the meaning of
each statement.  See <a href="#Semantics">Defining Language Semantics</a>.

     <br><dt>Shift<dd>A parser is said to shift when it makes the choice of analyzing
further input from the stream rather than reducing immediately some
already-recognized rule.  See <a href="#Algorithm">The Bison Parser Algorithm</a>.

     <br><dt>Single-character literal<dd>A single character that is recognized and interpreted as is. 
See <a href="#Grammar-in-Bison">From Formal Rules to Bison Input</a>.

     <br><dt>Start symbol<dd>The nonterminal symbol that stands for a complete valid utterance in
the language being parsed.  The start symbol is usually listed as the
first nonterminal symbol in a language specification. 
See <a href="#Start-Decl">The Start-Symbol</a>.

     <br><dt>Symbol table<dd>A data structure where symbol names and associated data are stored
during parsing to allow for recognition and use of existing
information in repeated uses of a symbol.  See <a href="#Multi_002dfunction-Calc">Multi-function Calc</a>.

     <br><dt>Syntax error<dd>An error encountered during parsing of an input stream due to invalid
syntax.  See <a href="#Error-Recovery">Error Recovery</a>.

     <br><dt>Token<dd>A basic, grammatically indivisible unit of a language.  The symbol
that describes a token in the grammar is a terminal symbol. 
The input of the Bison parser is a stream of tokens which comes from
the lexical analyzer.  See <a href="#Symbols">Symbols</a>.

     <br><dt>Terminal symbol<dd>A grammar symbol that has no rules in the grammar and therefore is
grammatically indivisible.  The piece of text it represents is a token. 
See <a href="#Language-and-Grammar">Languages and Context-Free Grammars</a>. 
</dl>

<div class="node">
<p><hr>
<a name="Copying-This-Manual"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="#Index">Index</a>,
Previous:&nbsp;<a rel="previous" accesskey="p" href="#FAQ">FAQ</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="appendix">Appendix C Copying This Manual</h2>

<ul class="menu">
<li><a accesskey="1" href="#GNU-Free-Documentation-License">GNU Free Documentation License</a>:   License for copying this manual. 
</ul>

<div class="node">
<p><hr>
<a name="GNU-Free-Documentation-License"></a>
Up:&nbsp;<a rel="up" accesskey="u" href="#Copying-This-Manual">Copying This Manual</a>

</div>

<h3 class="appendixsec">C.1 GNU Free Documentation License</h3>

<p><a name="index-FDL_002c-GNU-Free-Documentation-License-350"></a><div align="center">Version 1.2, November 2002</div>

<pre class="display">     Copyright &copy; 2000,2001,2002 Free Software Foundation, Inc.
     59 Temple Place, Suite 330, Boston, MA  02111-1307, USA
     
     Everyone is permitted to copy and distribute verbatim copies
     of this license document, but changing it is not allowed.
</pre>
     <ol type=1 start=0>
<li>PREAMBLE

     <p>The purpose of this License is to make a manual, textbook, or other
functional and useful document <dfn>free</dfn> in the sense of freedom: to
assure everyone the effective freedom to copy and redistribute it,
with or without modifying it, either commercially or noncommercially. 
Secondarily, this License preserves for the author and publisher a way
to get credit for their work, while not being considered responsible
for modifications made by others.

     <p>This License is a kind of &ldquo;copyleft&rdquo;, which means that derivative
works of the document must themselves be free in the same sense.  It
complements the GNU General Public License, which is a copyleft
license designed for free software.

     <p>We have designed this License in order to use it for manuals for free
software, because free software needs free documentation: a free
program should come with manuals providing the same freedoms that the
software does.  But this License is not limited to software manuals;
it can be used for any textual work, regardless of subject matter or
whether it is published as a printed book.  We recommend this License
principally for works whose purpose is instruction or reference.

     <li>APPLICABILITY AND DEFINITIONS

     <p>This License applies to any manual or other work, in any medium, that
contains a notice placed by the copyright holder saying it can be
distributed under the terms of this License.  Such a notice grants a
world-wide, royalty-free license, unlimited in duration, to use that
work under the conditions stated herein.  The &ldquo;Document&rdquo;, below,
refers to any such manual or work.  Any member of the public is a
licensee, and is addressed as &ldquo;you&rdquo;.  You accept the license if you
copy, modify or distribute the work in a way requiring permission
under copyright law.

     <p>A &ldquo;Modified Version&rdquo; of the Document means any work containing the
Document or a portion of it, either copied verbatim, or with
modifications and/or translated into another language.

     <p>A &ldquo;Secondary Section&rdquo; is a named appendix or a front-matter section
of the Document that deals exclusively with the relationship of the
publishers or authors of the Document to the Document's overall
subject (or to related matters) and contains nothing that could fall
directly within that overall subject.  (Thus, if the Document is in
part a textbook of mathematics, a Secondary Section may not explain
any mathematics.)  The relationship could be a matter of historical
connection with the subject or with related matters, or of legal,
commercial, philosophical, ethical or political position regarding
them.

     <p>The &ldquo;Invariant Sections&rdquo; are certain Secondary Sections whose titles
are designated, as being those of Invariant Sections, in the notice
that says that the Document is released under this License.  If a
section does not fit the above definition of Secondary then it is not
allowed to be designated as Invariant.  The Document may contain zero
Invariant Sections.  If the Document does not identify any Invariant
Sections then there are none.

     <p>The &ldquo;Cover Texts&rdquo; are certain short passages of text that are listed,
as Front-Cover Texts or Back-Cover Texts, in the notice that says that
the Document is released under this License.  A Front-Cover Text may
be at most 5 words, and a Back-Cover Text may be at most 25 words.

     <p>A &ldquo;Transparent&rdquo; copy of the Document means a machine-readable copy,
represented in a format whose specification is available to the
general public, that is suitable for revising the document
straightforwardly with generic text editors or (for images composed of
pixels) generic paint programs or (for drawings) some widely available
drawing editor, and that is suitable for input to text formatters or
for automatic translation to a variety of formats suitable for input
to text formatters.  A copy made in an otherwise Transparent file
format whose markup, or absence of markup, has been arranged to thwart
or discourage subsequent modification by readers is not Transparent. 
An image format is not Transparent if used for any substantial amount
of text.  A copy that is not &ldquo;Transparent&rdquo; is called &ldquo;Opaque&rdquo;.

     <p>Examples of suitable formats for Transparent copies include plain
<span class="sc">ascii</span> without markup, Texinfo input format, LaTeX input
format, <acronym>SGML</acronym> or <acronym>XML</acronym> using a publicly available
<acronym>DTD</acronym>, and standard-conforming simple <acronym>HTML</acronym>,
PostScript or <acronym>PDF</acronym> designed for human modification.  Examples
of transparent image formats include <acronym>PNG</acronym>, <acronym>XCF</acronym> and
<acronym>JPG</acronym>.  Opaque formats include proprietary formats that can be
read and edited only by proprietary word processors, <acronym>SGML</acronym> or
<acronym>XML</acronym> for which the <acronym>DTD</acronym> and/or processing tools are
not generally available, and the machine-generated <acronym>HTML</acronym>,
PostScript or <acronym>PDF</acronym> produced by some word processors for
output purposes only.

     <p>The &ldquo;Title Page&rdquo; means, for a printed book, the title page itself,
plus such following pages as are needed to hold, legibly, the material
this License requires to appear in the title page.  For works in
formats which do not have any title page as such, &ldquo;Title Page&rdquo; means
the text near the most prominent appearance of the work's title,
preceding the beginning of the body of the text.

     <p>A section &ldquo;Entitled XYZ&rdquo; means a named subunit of the Document whose
title either is precisely XYZ or contains XYZ in parentheses following
text that translates XYZ in another language.  (Here XYZ stands for a
specific section name mentioned below, such as &ldquo;Acknowledgements&rdquo;,
&ldquo;Dedications&rdquo;, &ldquo;Endorsements&rdquo;, or &ldquo;History&rdquo;.)  To &ldquo;Preserve the Title&rdquo;
of such a section when you modify the Document means that it remains a
section &ldquo;Entitled XYZ&rdquo; according to this definition.

     <p>The Document may include Warranty Disclaimers next to the notice which
states that this License applies to the Document.  These Warranty
Disclaimers are considered to be included by reference in this
License, but only as regards disclaiming warranties: any other
implication that these Warranty Disclaimers may have is void and has
no effect on the meaning of this License.

     <li>VERBATIM COPYING

     <p>You may copy and distribute the Document in any medium, either
commercially or noncommercially, provided that this License, the
copyright notices, and the license notice saying this License applies
to the Document are reproduced in all copies, and that you add no other
conditions whatsoever to those of this License.  You may not use
technical measures to obstruct or control the reading or further
copying of the copies you make or distribute.  However, you may accept
compensation in exchange for copies.  If you distribute a large enough
number of copies you must also follow the conditions in section 3.

     <p>You may also lend copies, under the same conditions stated above, and
you may publicly display copies.

     <li>COPYING IN QUANTITY

     <p>If you publish printed copies (or copies in media that commonly have
printed covers) of the Document, numbering more than 100, and the
Document's license notice requires Cover Texts, you must enclose the
copies in covers that carry, clearly and legibly, all these Cover
Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
the back cover.  Both covers must also clearly and legibly identify
you as the publisher of these copies.  The front cover must present
the full title with all words of the title equally prominent and
visible.  You may add other material on the covers in addition. 
Copying with changes limited to the covers, as long as they preserve
the title of the Document and satisfy these conditions, can be treated
as verbatim copying in other respects.

     <p>If the required texts for either cover are too voluminous to fit
legibly, you should put the first ones listed (as many as fit
reasonably) on the actual cover, and continue the rest onto adjacent
pages.

     <p>If you publish or distribute Opaque copies of the Document numbering
more than 100, you must either include a machine-readable Transparent
copy along with each Opaque copy, or state in or with each Opaque copy
a computer-network location from which the general network-using
public has access to download using public-standard network protocols
a complete Transparent copy of the Document, free of added material. 
If you use the latter option, you must take reasonably prudent steps,
when you begin distribution of Opaque copies in quantity, to ensure
that this Transparent copy will remain thus accessible at the stated
location until at least one year after the last time you distribute an
Opaque copy (directly or through your agents or retailers) of that
edition to the public.

     <p>It is requested, but not required, that you contact the authors of the
Document well before redistributing any large number of copies, to give
them a chance to provide you with an updated version of the Document.

     <li>MODIFICATIONS

     <p>You may copy and distribute a Modified Version of the Document under
the conditions of sections 2 and 3 above, provided that you release
the Modified Version under precisely this License, with the Modified
Version filling the role of the Document, thus licensing distribution
and modification of the Modified Version to whoever possesses a copy
of it.  In addition, you must do these things in the Modified Version:

          <ol type=A start=1>
<li>Use in the Title Page (and on the covers, if any) a title distinct
from that of the Document, and from those of previous versions
(which should, if there were any, be listed in the History section
of the Document).  You may use the same title as a previous version
if the original publisher of that version gives permission.

          <li>List on the Title Page, as authors, one or more persons or entities
responsible for authorship of the modifications in the Modified
Version, together with at least five of the principal authors of the
Document (all of its principal authors, if it has fewer than five),
unless they release you from this requirement.

          <li>State on the Title page the name of the publisher of the
Modified Version, as the publisher.

          <li>Preserve all the copyright notices of the Document.

          <li>Add an appropriate copyright notice for your modifications
adjacent to the other copyright notices.

          <li>Include, immediately after the copyright notices, a license notice
giving the public permission to use the Modified Version under the
terms of this License, in the form shown in the Addendum below.

          <li>Preserve in that license notice the full lists of Invariant Sections
and required Cover Texts given in the Document's license notice.

          <li>Include an unaltered copy of this License.

          <li>Preserve the section Entitled &ldquo;History&rdquo;, Preserve its Title, and add
to it an item stating at least the title, year, new authors, and
publisher of the Modified Version as given on the Title Page.  If
there is no section Entitled &ldquo;History&rdquo; in the Document, create one
stating the title, year, authors, and publisher of the Document as
given on its Title Page, then add an item describing the Modified
Version as stated in the previous sentence.

          <li>Preserve the network location, if any, given in the Document for
public access to a Transparent copy of the Document, and likewise
the network locations given in the Document for previous versions
it was based on.  These may be placed in the &ldquo;History&rdquo; section. 
You may omit a network location for a work that was published at
least four years before the Document itself, or if the original
publisher of the version it refers to gives permission.

          <li>For any section Entitled &ldquo;Acknowledgements&rdquo; or &ldquo;Dedications&rdquo;, Preserve
the Title of the section, and preserve in the section all the
substance and tone of each of the contributor acknowledgements and/or
dedications given therein.

          <li>Preserve all the Invariant Sections of the Document,
unaltered in their text and in their titles.  Section numbers
or the equivalent are not considered part of the section titles.

          <li>Delete any section Entitled &ldquo;Endorsements&rdquo;.  Such a section
may not be included in the Modified Version.

          <li>Do not retitle any existing section to be Entitled &ldquo;Endorsements&rdquo; or
to conflict in title with any Invariant Section.

          <li>Preserve any Warranty Disclaimers.
          </ol>

     <p>If the Modified Version includes new front-matter sections or
appendices that qualify as Secondary Sections and contain no material
copied from the Document, you may at your option designate some or all
of these sections as invariant.  To do this, add their titles to the
list of Invariant Sections in the Modified Version's license notice. 
These titles must be distinct from any other section titles.

     <p>You may add a section Entitled &ldquo;Endorsements&rdquo;, provided it contains
nothing but endorsements of your Modified Version by various
parties&mdash;for example, statements of peer review or that the text has
been approved by an organization as the authoritative definition of a
standard.

     <p>You may add a passage of up to five words as a Front-Cover Text, and a
passage of up to 25 words as a Back-Cover Text, to the end of the list
of Cover Texts in the Modified Version.  Only one passage of
Front-Cover Text and one of Back-Cover Text may be added by (or
through arrangements made by) any one entity.  If the Document already
includes a cover text for the same cover, previously added by you or
by arrangement made by the same entity you are acting on behalf of,
you may not add another; but you may replace the old one, on explicit
permission from the previous publisher that added the old one.

     <p>The author(s) and publisher(s) of the Document do not by this License
give permission to use their names for publicity for or to assert or
imply endorsement of any Modified Version.

     <li>COMBINING DOCUMENTS

     <p>You may combine the Document with other documents released under this
License, under the terms defined in section 4 above for modified
versions, provided that you include in the combination all of the
Invariant Sections of all of the original documents, unmodified, and
list them all as Invariant Sections of your combined work in its
license notice, and that you preserve all their Warranty Disclaimers.

     <p>The combined work need only contain one copy of this License, and
multiple identical Invariant Sections may be replaced with a single
copy.  If there are multiple Invariant Sections with the same name but
different contents, make the title of each such section unique by
adding at the end of it, in parentheses, the name of the original
author or publisher of that section if known, or else a unique number. 
Make the same adjustment to the section titles in the list of
Invariant Sections in the license notice of the combined work.

     <p>In the combination, you must combine any sections Entitled &ldquo;History&rdquo;
in the various original documents, forming one section Entitled
&ldquo;History&rdquo;; likewise combine any sections Entitled &ldquo;Acknowledgements&rdquo;,
and any sections Entitled &ldquo;Dedications&rdquo;.  You must delete all
sections Entitled &ldquo;Endorsements.&rdquo;

     <li>COLLECTIONS OF DOCUMENTS

     <p>You may make a collection consisting of the Document and other documents
released under this License, and replace the individual copies of this
License in the various documents with a single copy that is included in
the collection, provided that you follow the rules of this License for
verbatim copying of each of the documents in all other respects.

     <p>You may extract a single document from such a collection, and distribute
it individually under this License, provided you insert a copy of this
License into the extracted document, and follow this License in all
other respects regarding verbatim copying of that document.

     <li>AGGREGATION WITH INDEPENDENT WORKS

     <p>A compilation of the Document or its derivatives with other separate
and independent documents or works, in or on a volume of a storage or
distribution medium, is called an &ldquo;aggregate&rdquo; if the copyright
resulting from the compilation is not used to limit the legal rights
of the compilation's users beyond what the individual works permit. 
When the Document is included an aggregate, this License does not
apply to the other works in the aggregate which are not themselves
derivative works of the Document.

     <p>If the Cover Text requirement of section 3 is applicable to these
copies of the Document, then if the Document is less than one half of
the entire aggregate, the Document's Cover Texts may be placed on
covers that bracket the Document within the aggregate, or the
electronic equivalent of covers if the Document is in electronic form. 
Otherwise they must appear on printed covers that bracket the whole
aggregate.

     <li>TRANSLATION

     <p>Translation is considered a kind of modification, so you may
distribute translations of the Document under the terms of section 4. 
Replacing Invariant Sections with translations requires special
permission from their copyright holders, but you may include
translations of some or all Invariant Sections in addition to the
original versions of these Invariant Sections.  You may include a
translation of this License, and all the license notices in the
Document, and any Warrany Disclaimers, provided that you also include
the original English version of this License and the original versions
of those notices and disclaimers.  In case of a disagreement between
the translation and the original version of this License or a notice
or disclaimer, the original version will prevail.

     <p>If a section in the Document is Entitled &ldquo;Acknowledgements&rdquo;,
&ldquo;Dedications&rdquo;, or &ldquo;History&rdquo;, the requirement (section 4) to Preserve
its Title (section 1) will typically require changing the actual
title.

     <li>TERMINATION

     <p>You may not copy, modify, sublicense, or distribute the Document except
as expressly provided for under this License.  Any other attempt to
copy, modify, sublicense or distribute the Document is void, and will
automatically terminate your rights under this License.  However,
parties who have received copies, or rights, from you under this
License will not have their licenses terminated so long as such
parties remain in full compliance.

     <li>FUTURE REVISIONS OF THIS LICENSE

     <p>The Free Software Foundation may publish new, revised versions
of the GNU Free Documentation License from time to time.  Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.  See
<a href="http://www.gnu.org/copyleft/">http://www.gnu.org/copyleft/</a>.

     <p>Each version of the License is given a distinguishing version number. 
If the Document specifies that a particular numbered version of this
License &ldquo;or any later version&rdquo; applies to it, you have the option of
following the terms and conditions either of that specified version or
of any later version that has been published (not as a draft) by the
Free Software Foundation.  If the Document does not specify a version
number of this License, you may choose any version ever published (not
as a draft) by the Free Software Foundation.
        </ol>

<h4 class="appendixsubsec">C.1.1 ADDENDUM: How to use this License for your documents</h4>

<p>To use this License in a document you have written, include a copy of
the License in the document and put the following copyright and
license notices just after the title page:

<pre class="smallexample">       Copyright (C)  <var>year</var>  <var>your name</var>.
       Permission is granted to copy, distribute and/or modify this document
       under the terms of the GNU Free Documentation License, Version 1.2
       or any later version published by the Free Software Foundation;
       with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
       A copy of the license is included in the section entitled ``GNU
       Free Documentation License''.
</pre>
   <p>If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
replace the &ldquo;with...Texts.&rdquo; line with this:

<pre class="smallexample">         with the Invariant Sections being <var>list their titles</var>, with
         the Front-Cover Texts being <var>list</var>, and with the Back-Cover Texts
         being <var>list</var>.
</pre>
   <p>If you have Invariant Sections without Cover Texts, or some other
combination of the three, merge those two alternatives to suit the
situation.

   <p>If your document contains nontrivial examples of program code, we
recommend releasing these examples in parallel under your choice of
free software license, such as the GNU General Public License,
to permit their use in free software.

<!-- Local Variables: -->
<!-- ispell-local-pdict: "ispell-dict" -->
<!-- End: -->
<div class="node">
<p><hr>
<a name="Index"></a>
Previous:&nbsp;<a rel="previous" accesskey="p" href="#Copying-This-Manual">Copying This Manual</a>,
Up:&nbsp;<a rel="up" accesskey="u" href="#Top">Top</a>

</div>

<h2 class="unnumbered">Index</h2>

<ul class="index-cp" compact>
<li><a href="#index-action-103">action</a>: <a href="#Actions">Actions</a></li>
<li><a href="#index-action-data-types-107">action data types</a>: <a href="#Action-Types">Action Types</a></li>
<li><a href="#index-action-features-summary-196">action features summary</a>: <a href="#Action-Features">Action Features</a></li>
<li><a href="#index-actions-in-mid_002drule-109">actions in mid-rule</a>: <a href="#Mid_002dRule-Actions">Mid-Rule Actions</a></li>
<li><a href="#index-actions_002c-location-117">actions, location</a>: <a href="#Actions-and-Locations">Actions and Locations</a></li>
<li><a href="#index-actions_002c-semantic-23">actions, semantic</a>: <a href="#Semantic-Actions">Semantic Actions</a></li>
<li><a href="#index-additional-C-code-section-76">additional C code section</a>: <a href="#Epilogue">Epilogue</a></li>
<li><a href="#index-algorithm-of-parser-218">algorithm of parser</a>: <a href="#Algorithm">Algorithm</a></li>
<li><a href="#index-ambiguous-grammars-249">ambiguous grammars</a>: <a href="#Generalized-LR-Parsing">Generalized LR Parsing</a></li>
<li><a href="#index-ambiguous-grammars-10">ambiguous grammars</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
<li><a href="#index-associativity-231">associativity</a>: <a href="#Why-Precedence">Why Precedence</a></li>
<li><a href="#index-Backus_002dNaur-form-5">Backus-Naur form</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
<li><a href="#index-Bison-declaration-summary-152">Bison declaration summary</a>: <a href="#Decl-Summary">Decl Summary</a></li>
<li><a href="#index-Bison-declarations-122">Bison declarations</a>: <a href="#Declarations">Declarations</a></li>
<li><a href="#index-Bison-declarations-_0028introduction_0029-72">Bison declarations (introduction)</a>: <a href="#Bison-Declarations">Bison Declarations</a></li>
<li><a href="#index-Bison-grammar-17">Bison grammar</a>: <a href="#Grammar-in-Bison">Grammar in Bison</a></li>
<li><a href="#index-Bison-invocation-284">Bison invocation</a>: <a href="#Invocation">Invocation</a></li>
<li><a href="#index-Bison-parser-34">Bison parser</a>: <a href="#Bison-Parser">Bison Parser</a></li>
<li><a href="#index-Bison-parser-algorithm-217">Bison parser algorithm</a>: <a href="#Algorithm">Algorithm</a></li>
<li><a href="#index-Bison-symbols_002c-table-of-288">Bison symbols, table of</a>: <a href="#Table-of-Symbols">Table of Symbols</a></li>
<li><a href="#index-Bison-utility-35">Bison utility</a>: <a href="#Bison-Parser">Bison Parser</a></li>
<li><a href="#index-g_t_0040acronym_007bBNF_007d-4"><acronym>BNF</acronym></a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
<li><a href="#index-C-code_002c-section-for-additional-78">C code, section for additional</a>: <a href="#Epilogue">Epilogue</a></li>
<li><a href="#index-C_002dlanguage-interface-176">C-language interface</a>: <a href="#Interface">Interface</a></li>
<li><a href="#index-g_t_0040code_007bcalc_007d-58"><code>calc</code></a>: <a href="#Infix-Calc">Infix Calc</a></li>
<li><a href="#index-calculator_002c-infix-notation-59">calculator, infix notation</a>: <a href="#Infix-Calc">Infix Calc</a></li>
<li><a href="#index-calculator_002c-location-tracking-63">calculator, location tracking</a>: <a href="#Location-Tracking-Calc">Location Tracking Calc</a></li>
<li><a href="#index-calculator_002c-multi_002dfunction-66">calculator, multi-function</a>: <a href="#Multi_002dfunction-Calc">Multi-function Calc</a></li>
<li><a href="#index-calculator_002c-simple-49">calculator, simple</a>: <a href="#RPN-Calc">RPN Calc</a></li>
<li><a href="#index-character-token-83">character token</a>: <a href="#Symbols">Symbols</a></li>
<li><a href="#index-compiling-the-parser-56">compiling the parser</a>: <a href="#Rpcalc-Compile">Rpcalc Compile</a></li>
<li><a href="#index-conflicts-225">conflicts</a>: <a href="#Shift_002fReduce">Shift/Reduce</a></li>
<li><a href="#index-conflicts-27">conflicts</a>: <a href="#GLR-Parsers">GLR Parsers</a></li>
<li><a href="#index-conflicts_002c-reduce_002freduce-244">conflicts, reduce/reduce</a>: <a href="#Reduce_002fReduce">Reduce/Reduce</a></li>
<li><a href="#index-conflicts_002c-suppressing-warnings-of-143">conflicts, suppressing warnings of</a>: <a href="#Expect-Decl">Expect Decl</a></li>
<li><a href="#index-context_002ddependent-precedence-235">context-dependent precedence</a>: <a href="#Contextual-Precedence">Contextual Precedence</a></li>
<li><a href="#index-context_002dfree-grammar-2">context-free grammar</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
<li><a href="#index-controlling-function-52">controlling function</a>: <a href="#Rpcalc-Main">Rpcalc Main</a></li>
<li><a href="#index-core_002c-item-set-273">core, item set</a>: <a href="#Understanding">Understanding</a></li>
<li><a href="#index-dangling-_0040code_007belse_007d-227">dangling <code>else</code></a>: <a href="#Shift_002fReduce">Shift/Reduce</a></li>
<li><a href="#index-data-type-of-locations-114">data type of locations</a>: <a href="#Location-Type">Location Type</a></li>
<li><a href="#index-data-types-in-actions-108">data types in actions</a>: <a href="#Action-Types">Action Types</a></li>
<li><a href="#index-data-types-of-semantic-values-101">data types of semantic values</a>: <a href="#Value-Type">Value Type</a></li>
<li><a href="#index-debugging-278">debugging</a>: <a href="#Tracing">Tracing</a></li>
<li><a href="#index-declaration-summary-153">declaration summary</a>: <a href="#Decl-Summary">Decl Summary</a></li>
<li><a href="#index-declarations-71">declarations</a>: <a href="#Prologue">Prologue</a></li>
<li><a href="#index-declarations-section-69">declarations section</a>: <a href="#Prologue">Prologue</a></li>
<li><a href="#index-declarations_002c-Bison-121">declarations, Bison</a>: <a href="#Declarations">Declarations</a></li>
<li><a href="#index-declarations_002c-Bison-_0028introduction_0029-73">declarations, Bison (introduction)</a>: <a href="#Bison-Declarations">Bison Declarations</a></li>
<li><a href="#index-declaring-literal-string-tokens-125">declaring literal string tokens</a>: <a href="#Token-Decl">Token Decl</a></li>
<li><a href="#index-declaring-operator-precedence-128">declaring operator precedence</a>: <a href="#Precedence-Decl">Precedence Decl</a></li>
<li><a href="#index-declaring-the-start-symbol-145">declaring the start symbol</a>: <a href="#Start-Decl">Start Decl</a></li>
<li><a href="#index-declaring-token-type-names-123">declaring token type names</a>: <a href="#Token-Decl">Token Decl</a></li>
<li><a href="#index-declaring-value-types-130">declaring value types</a>: <a href="#Union-Decl">Union Decl</a></li>
<li><a href="#index-declaring-value-types_002c-nonterminals-133">declaring value types, nonterminals</a>: <a href="#Type-Decl">Type Decl</a></li>
<li><a href="#index-default-action-106">default action</a>: <a href="#Actions">Actions</a></li>
<li><a href="#index-default-data-type-102">default data type</a>: <a href="#Value-Type">Value Type</a></li>
<li><a href="#index-default-location-type-115">default location type</a>: <a href="#Location-Type">Location Type</a></li>
<li><a href="#index-default-stack-limit-255">default stack limit</a>: <a href="#Stack-Overflow">Stack Overflow</a></li>
<li><a href="#index-default-start-symbol-147">default start symbol</a>: <a href="#Start-Decl">Start Decl</a></li>
<li><a href="#index-defining-language-semantics-97">defining language semantics</a>: <a href="#Semantics">Semantics</a></li>
<li><a href="#index-g_t_0040code_007belse_007d_002c-dangling-228"><code>else</code>, dangling</a>: <a href="#Shift_002fReduce">Shift/Reduce</a></li>
<li><a href="#index-epilogue-77">epilogue</a>: <a href="#Epilogue">Epilogue</a></li>
<li><a href="#index-error-recovery-257">error recovery</a>: <a href="#Error-Recovery">Error Recovery</a></li>
<li><a href="#index-error-recovery_002c-simple-60">error recovery, simple</a>: <a href="#Simple-Error-Recovery">Simple Error Recovery</a></li>
<li><a href="#index-error-reporting-function-189">error reporting function</a>: <a href="#Error-Reporting">Error Reporting</a></li>
<li><a href="#index-error-reporting-routine-54">error reporting routine</a>: <a href="#Rpcalc-Error">Rpcalc Error</a></li>
<li><a href="#index-examples_002c-simple-45">examples, simple</a>: <a href="#Examples">Examples</a></li>
<li><a href="#index-exercises-68">exercises</a>: <a href="#Exercises">Exercises</a></li>
<li><a href="#index-FDL_002c-GNU-Free-Documentation-License-350">FDL, GNU Free Documentation License</a>: <a href="#GNU-Free-Documentation-License">GNU Free Documentation License</a></li>
<li><a href="#index-file-format-41">file format</a>: <a href="#Grammar-Layout">Grammar Layout</a></li>
<li><a href="#index-finite_002dstate-machine-240">finite-state machine</a>: <a href="#Parser-States">Parser States</a></li>
<li><a href="#index-formal-grammar-19">formal grammar</a>: <a href="#Grammar-in-Bison">Grammar in Bison</a></li>
<li><a href="#index-format-of-grammar-file-42">format of grammar file</a>: <a href="#Grammar-Layout">Grammar Layout</a></li>
<li><a href="#index-freeing-discarded-symbols-136">freeing discarded symbols</a>: <a href="#Destructor-Decl">Destructor Decl</a></li>
<li><a href="#index-frequently-asked-questions-286">frequently asked questions</a>: <a href="#FAQ">FAQ</a></li>
<li><a href="#index-generalized-_0040acronym_007bLR_007d-_0028_0040acronym_007bGLR_007d_0029-parsing-248">generalized <acronym>LR</acronym> (<acronym>GLR</acronym>) parsing</a>: <a href="#Generalized-LR-Parsing">Generalized LR Parsing</a></li>
<li><a href="#index-generalized-_0040acronym_007bLR_007d-_0028_0040acronym_007bGLR_007d_0029-parsing-25">generalized <acronym>LR</acronym> (<acronym>GLR</acronym>) parsing</a>: <a href="#GLR-Parsers">GLR Parsers</a></li>
<li><a href="#index-generalized-_0040acronym_007bLR_007d-_0028_0040acronym_007bGLR_007d_0029-parsing-9">generalized <acronym>LR</acronym> (<acronym>GLR</acronym>) parsing</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
<li><a href="#index-glossary-349">glossary</a>: <a href="#Glossary">Glossary</a></li>
<li><a href="#index-g_t_0040acronym_007bGLR_007d-parsers-and-_0040code_007binline_007d-30"><acronym>GLR</acronym> parsers and <code>inline</code></a>: <a href="#GLR-Parsers">GLR Parsers</a></li>
<li><a href="#index-g_t_0040acronym_007bGLR_007d-parsing-247"><acronym>GLR</acronym> parsing</a>: <a href="#Generalized-LR-Parsing">Generalized LR Parsing</a></li>
<li><a href="#index-g_t_0040acronym_007bGLR_007d-parsing-24"><acronym>GLR</acronym> parsing</a>: <a href="#GLR-Parsers">GLR Parsers</a></li>
<li><a href="#index-g_t_0040acronym_007bGLR_007d-parsing-8"><acronym>GLR</acronym> parsing</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
<li><a href="#index-grammar-file-40">grammar file</a>: <a href="#Grammar-Layout">Grammar Layout</a></li>
<li><a href="#index-grammar-rule-syntax-90">grammar rule syntax</a>: <a href="#Rules">Rules</a></li>
<li><a href="#index-grammar-rules-section-74">grammar rules section</a>: <a href="#Grammar-Rules">Grammar Rules</a></li>
<li><a href="#index-grammar_002c-Bison-18">grammar, Bison</a>: <a href="#Grammar-in-Bison">Grammar in Bison</a></li>
<li><a href="#index-grammar_002c-context_002dfree-3">grammar, context-free</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
<li><a href="#index-grouping_002c-syntactic-15">grouping, syntactic</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
<li><a href="#index-g_t_0040code_007bincline_007d-29"><code>incline</code></a>: <a href="#GLR-Parsers">GLR Parsers</a></li>
<li><a href="#index-infix-notation-calculator-57">infix notation calculator</a>: <a href="#Infix-Calc">Infix Calc</a></li>
<li><a href="#index-interface-177">interface</a>: <a href="#Interface">Interface</a></li>
<li><a href="#index-introduction-1">introduction</a>: <a href="#Introduction">Introduction</a></li>
<li><a href="#index-invoking-Bison-283">invoking Bison</a>: <a href="#Invocation">Invocation</a></li>
<li><a href="#index-item-270">item</a>: <a href="#Understanding">Understanding</a></li>
<li><a href="#index-item-set-core-274">item set core</a>: <a href="#Understanding">Understanding</a></li>
<li><a href="#index-kernel_002c-item-set-275">kernel, item set</a>: <a href="#Understanding">Understanding</a></li>
<li><a href="#index-g_t_0040acronym_007bLALR_007d_00281_0029-246"><acronym>LALR</acronym>(1)</a>: <a href="#Mystery-Conflicts">Mystery Conflicts</a></li>
<li><a href="#index-g_t_0040acronym_007bLALR_007d_00281_0029-grammars-6"><acronym>LALR</acronym>(1) grammars</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
<li><a href="#index-language-semantics_002c-defining-98">language semantics, defining</a>: <a href="#Semantics">Semantics</a></li>
<li><a href="#index-layout-of-Bison-grammar-43">layout of Bison grammar</a>: <a href="#Grammar-Layout">Grammar Layout</a></li>
<li><a href="#index-left-recursion-94">left recursion</a>: <a href="#Recursion">Recursion</a></li>
<li><a href="#index-lexical-analyzer-185">lexical analyzer</a>: <a href="#Lexical">Lexical</a></li>
<li><a href="#index-lexical-analyzer_002c-purpose-36">lexical analyzer, purpose</a>: <a href="#Bison-Parser">Bison Parser</a></li>
<li><a href="#index-lexical-analyzer_002c-writing-51">lexical analyzer, writing</a>: <a href="#Rpcalc-Lexer">Rpcalc Lexer</a></li>
<li><a href="#index-lexical-tie_002din-263">lexical tie-in</a>: <a href="#Lexical-Tie_002dins">Lexical Tie-ins</a></li>
<li><a href="#index-literal-string-token-87">literal string token</a>: <a href="#Symbols">Symbols</a></li>
<li><a href="#index-literal-token-84">literal token</a>: <a href="#Symbols">Symbols</a></li>
<li><a href="#index-location-111">location</a>: <a href="#Locations">Locations</a></li>
<li><a href="#index-location-31">location</a>: <a href="#Locations-Overview">Locations Overview</a></li>
<li><a href="#index-location-actions-116">location actions</a>: <a href="#Actions-and-Locations">Actions and Locations</a></li>
<li><a href="#index-location-tracking-calculator-61">location tracking calculator</a>: <a href="#Location-Tracking-Calc">Location Tracking Calc</a></li>
<li><a href="#index-look_002dahead-token-223">look-ahead token</a>: <a href="#Look_002dAhead">Look-Ahead</a></li>
<li><a href="#index-g_t_0040acronym_007bLR_007d_00281_0029-245"><acronym>LR</acronym>(1)</a>: <a href="#Mystery-Conflicts">Mystery Conflicts</a></li>
<li><a href="#index-g_t_0040acronym_007bLR_007d_00281_0029-grammars-7"><acronym>LR</acronym>(1) grammars</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
<li><a href="#index-g_t_0040code_007bltcalc_007d-62"><code>ltcalc</code></a>: <a href="#Location-Tracking-Calc">Location Tracking Calc</a></li>
<li><a href="#index-main-function-in-simple-example-53">main function in simple example</a>: <a href="#Rpcalc-Main">Rpcalc Main</a></li>
<li><a href="#index-g_t_0040code_007bmfcalc_007d-65"><code>mfcalc</code></a>: <a href="#Multi_002dfunction-Calc">Multi-function Calc</a></li>
<li><a href="#index-mid_002drule-actions-110">mid-rule actions</a>: <a href="#Mid_002dRule-Actions">Mid-Rule Actions</a></li>
<li><a href="#index-multi_002dfunction-calculator-64">multi-function calculator</a>: <a href="#Multi_002dfunction-Calc">Multi-function Calc</a></li>
<li><a href="#index-multicharacter-literal-88">multicharacter literal</a>: <a href="#Symbols">Symbols</a></li>
<li><a href="#index-mutual-recursion-96">mutual recursion</a>: <a href="#Recursion">Recursion</a></li>
<li><a href="#index-non_002ddeterministic-parsing-250">non-deterministic parsing</a>: <a href="#Generalized-LR-Parsing">Generalized LR Parsing</a></li>
<li><a href="#index-non_002ddeterministic-parsing-11">non-deterministic parsing</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
<li><a href="#index-nonterminal-symbol-79">nonterminal symbol</a>: <a href="#Symbols">Symbols</a></li>
<li><a href="#index-nonterminal_002c-useless-266">nonterminal, useless</a>: <a href="#Understanding">Understanding</a></li>
<li><a href="#index-operator-precedence-229">operator precedence</a>: <a href="#Precedence">Precedence</a></li>
<li><a href="#index-operator-precedence_002c-declaring-129">operator precedence, declaring</a>: <a href="#Precedence-Decl">Precedence Decl</a></li>
<li><a href="#index-options-for-invoking-Bison-285">options for invoking Bison</a>: <a href="#Invocation">Invocation</a></li>
<li><a href="#index-overflow-of-parser-stack-253">overflow of parser stack</a>: <a href="#Stack-Overflow">Stack Overflow</a></li>
<li><a href="#index-parse-error-191">parse error</a>: <a href="#Error-Reporting">Error Reporting</a></li>
<li><a href="#index-parser-37">parser</a>: <a href="#Bison-Parser">Bison Parser</a></li>
<li><a href="#index-parser-stack-221">parser stack</a>: <a href="#Algorithm">Algorithm</a></li>
<li><a href="#index-parser-stack-overflow-252">parser stack overflow</a>: <a href="#Stack-Overflow">Stack Overflow</a></li>
<li><a href="#index-parser-state-241">parser state</a>: <a href="#Parser-States">Parser States</a></li>
<li><a href="#index-pointed-rule-271">pointed rule</a>: <a href="#Understanding">Understanding</a></li>
<li><a href="#index-polish-notation-calculator-47">polish notation calculator</a>: <a href="#RPN-Calc">RPN Calc</a></li>
<li><a href="#index-position_002c-textual-113">position, textual</a>: <a href="#Locations">Locations</a></li>
<li><a href="#index-position_002c-textual-33">position, textual</a>: <a href="#Locations-Overview">Locations Overview</a></li>
<li><a href="#index-precedence-declarations-127">precedence declarations</a>: <a href="#Precedence-Decl">Precedence Decl</a></li>
<li><a href="#index-precedence-of-operators-230">precedence of operators</a>: <a href="#Precedence">Precedence</a></li>
<li><a href="#index-precedence_002c-context_002ddependent-237">precedence, context-dependent</a>: <a href="#Contextual-Precedence">Contextual Precedence</a></li>
<li><a href="#index-precedence_002c-unary-operator-238">precedence, unary operator</a>: <a href="#Contextual-Precedence">Contextual Precedence</a></li>
<li><a href="#index-preventing-warnings-about-conflicts-141">preventing warnings about conflicts</a>: <a href="#Expect-Decl">Expect Decl</a></li>
<li><a href="#index-Prologue-70">Prologue</a>: <a href="#Prologue">Prologue</a></li>
<li><a href="#index-pure-parser-150">pure parser</a>: <a href="#Pure-Decl">Pure Decl</a></li>
<li><a href="#index-questions-287">questions</a>: <a href="#FAQ">FAQ</a></li>
<li><a href="#index-recovery-from-errors-258">recovery from errors</a>: <a href="#Error-Recovery">Error Recovery</a></li>
<li><a href="#index-recursive-rule-93">recursive rule</a>: <a href="#Recursion">Recursion</a></li>
<li><a href="#index-reduce_002freduce-conflict-243">reduce/reduce conflict</a>: <a href="#Reduce_002fReduce">Reduce/Reduce</a></li>
<li><a href="#index-reduction-220">reduction</a>: <a href="#Algorithm">Algorithm</a></li>
<li><a href="#index-reentrant-parser-149">reentrant parser</a>: <a href="#Pure-Decl">Pure Decl</a></li>
<li><a href="#index-reverse-polish-notation-46">reverse polish notation</a>: <a href="#RPN-Calc">RPN Calc</a></li>
<li><a href="#index-right-recursion-95">right recursion</a>: <a href="#Recursion">Recursion</a></li>
<li><a href="#index-g_t_0040code_007brpcalc_007d-48"><code>rpcalc</code></a>: <a href="#RPN-Calc">RPN Calc</a></li>
<li><a href="#index-rule-syntax-89">rule syntax</a>: <a href="#Rules">Rules</a></li>
<li><a href="#index-rule_002c-pointed-272">rule, pointed</a>: <a href="#Understanding">Understanding</a></li>
<li><a href="#index-rule_002c-useless-268">rule, useless</a>: <a href="#Understanding">Understanding</a></li>
<li><a href="#index-rules-section-for-grammar-75">rules section for grammar</a>: <a href="#Grammar-Rules">Grammar Rules</a></li>
<li><a href="#index-running-Bison-_0028introduction_0029-55">running Bison (introduction)</a>: <a href="#Rpcalc-Gen">Rpcalc Gen</a></li>
<li><a href="#index-semantic-actions-22">semantic actions</a>: <a href="#Semantic-Actions">Semantic Actions</a></li>
<li><a href="#index-semantic-value-20">semantic value</a>: <a href="#Semantic-Values">Semantic Values</a></li>
<li><a href="#index-semantic-value-type-99">semantic value type</a>: <a href="#Value-Type">Value Type</a></li>
<li><a href="#index-shift_002freduce-conflicts-226">shift/reduce conflicts</a>: <a href="#Shift_002fReduce">Shift/Reduce</a></li>
<li><a href="#index-shift_002freduce-conflicts-28">shift/reduce conflicts</a>: <a href="#GLR-Parsers">GLR Parsers</a></li>
<li><a href="#index-shifting-219">shifting</a>: <a href="#Algorithm">Algorithm</a></li>
<li><a href="#index-simple-examples-44">simple examples</a>: <a href="#Examples">Examples</a></li>
<li><a href="#index-single_002dcharacter-literal-85">single-character literal</a>: <a href="#Symbols">Symbols</a></li>
<li><a href="#index-stack-overflow-251">stack overflow</a>: <a href="#Stack-Overflow">Stack Overflow</a></li>
<li><a href="#index-stack_002c-parser-222">stack, parser</a>: <a href="#Algorithm">Algorithm</a></li>
<li><a href="#index-stages-in-using-Bison-38">stages in using Bison</a>: <a href="#Stages">Stages</a></li>
<li><a href="#index-start-symbol-16">start symbol</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
<li><a href="#index-start-symbol_002c-declaring-146">start symbol, declaring</a>: <a href="#Start-Decl">Start Decl</a></li>
<li><a href="#index-state-_0028of-parser_0029-242">state (of parser)</a>: <a href="#Parser-States">Parser States</a></li>
<li><a href="#index-string-token-86">string token</a>: <a href="#Symbols">Symbols</a></li>
<li><a href="#index-summary_002c-action-features-195">summary, action features</a>: <a href="#Action-Features">Action Features</a></li>
<li><a href="#index-summary_002c-Bison-declaration-154">summary, Bison declaration</a>: <a href="#Decl-Summary">Decl Summary</a></li>
<li><a href="#index-suppressing-conflict-warnings-140">suppressing conflict warnings</a>: <a href="#Expect-Decl">Expect Decl</a></li>
<li><a href="#index-symbol-82">symbol</a>: <a href="#Symbols">Symbols</a></li>
<li><a href="#index-symbol-table-example-67">symbol table example</a>: <a href="#Mfcalc-Symtab">Mfcalc Symtab</a></li>
<li><a href="#index-symbols-_0028abstract_0029-12">symbols (abstract)</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
<li><a href="#index-symbols-in-Bison_002c-table-of-289">symbols in Bison, table of</a>: <a href="#Table-of-Symbols">Table of Symbols</a></li>
<li><a href="#index-syntactic-grouping-14">syntactic grouping</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
<li><a href="#index-syntax-error-192">syntax error</a>: <a href="#Error-Reporting">Error Reporting</a></li>
<li><a href="#index-syntax-of-grammar-rules-91">syntax of grammar rules</a>: <a href="#Rules">Rules</a></li>
<li><a href="#index-terminal-symbol-80">terminal symbol</a>: <a href="#Symbols">Symbols</a></li>
<li><a href="#index-textual-position-112">textual position</a>: <a href="#Locations">Locations</a></li>
<li><a href="#index-textual-position-32">textual position</a>: <a href="#Locations-Overview">Locations Overview</a></li>
<li><a href="#index-token-13">token</a>: <a href="#Language-and-Grammar">Language and Grammar</a></li>
<li><a href="#index-token-type-81">token type</a>: <a href="#Symbols">Symbols</a></li>
<li><a href="#index-token-type-names_002c-declaring-124">token type names, declaring</a>: <a href="#Token-Decl">Token Decl</a></li>
<li><a href="#index-token_002c-useless-264">token, useless</a>: <a href="#Understanding">Understanding</a></li>
<li><a href="#index-tracing-the-parser-279">tracing the parser</a>: <a href="#Tracing">Tracing</a></li>
<li><a href="#index-unary-operator-precedence-236">unary operator precedence</a>: <a href="#Contextual-Precedence">Contextual Precedence</a></li>
<li><a href="#index-useless-nonterminal-267">useless nonterminal</a>: <a href="#Understanding">Understanding</a></li>
<li><a href="#index-useless-rule-269">useless rule</a>: <a href="#Understanding">Understanding</a></li>
<li><a href="#index-useless-token-265">useless token</a>: <a href="#Understanding">Understanding</a></li>
<li><a href="#index-using-Bison-39">using Bison</a>: <a href="#Stages">Stages</a></li>
<li><a href="#index-value-type_002c-semantic-100">value type, semantic</a>: <a href="#Value-Type">Value Type</a></li>
<li><a href="#index-value-types_002c-declaring-131">value types, declaring</a>: <a href="#Union-Decl">Union Decl</a></li>
<li><a href="#index-value-types_002c-nonterminals_002c-declaring-134">value types, nonterminals, declaring</a>: <a href="#Type-Decl">Type Decl</a></li>
<li><a href="#index-value_002c-semantic-21">value, semantic</a>: <a href="#Semantic-Values">Semantic Values</a></li>
<li><a href="#index-warnings_002c-preventing-142">warnings, preventing</a>: <a href="#Expect-Decl">Expect Decl</a></li>
<li><a href="#index-writing-a-lexical-analyzer-50">writing a lexical analyzer</a>: <a href="#Rpcalc-Lexer">Rpcalc Lexer</a></li>
   </ul></body></html>

